赞
踩
单引号或双引号,三引号都可以来定义一个字符串。
三引号允许换行。
- print('''hello
- world!''')
| 转义字符 | 功能描述 |
| \ | 当位于末尾时代表转接下一行 |
| \\ | 反斜杠符号 |
| \' | 单引号符号 |
| \\" | 双引号符号 |
| \a | 响铃 |
| \b | 退格BackSpace |
| \e | 转义 |
| \n | 换行 |
| \v | 纵向制表 |
| \t | 横向制表 |
| \r | 回车 |
| \f | 换页 |
| \000 | 空 |
| \0yy | 八进制数,其中y代表字符,比如\012代表换行 |
| \xyy | 十六进制数,其中yy代表字符,比如\x44 代表D |
如果只是想单纯的正常显示字符,可以在字符串前加r或者将转义字符的\用\\替换。
比如
- print(r'hello \n world!')
- print('hello \\n world!')
- 输出结果:
- hello \n world!
- hello \n world!
格式控制方式:
%[(name)][flag][width].[precision]typecode
- print("%10c"%65)
- print("%10s"%"hi")
- print("%10.3f"%10)
- print("%15.3e"%65.787383749784983) #默认保留6位
-
- # 多个占位符的操作
- name = "bruce"
- salary = 1000
- print("我的名字是:%(name2)s,收入是%(sal)-10.2f"%{"name2":name,"sal":float(salary)})
- # 注意:多个占位符的变量要写成json的格式,也可以写成元组的形式,例如
- print("我的名字是:%s,收入是%-10.2f"%(name,float(salary)))
format的格式
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
arg_name ::= [identifier | integer]
attribute_name ::= identifier
element_index ::= integer | index_string
index_string ::= <any source character except "]"> +
conversion ::= "r" | "s" | "a"
format_spec ::= <described in the next section>
format_spec 的格式
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^" #左移,右移,填充‘=’,居中
sign ::= "+" | "-" | " " #'!s'它调用str(),'!r'调用repr(),'!a'调用ascii()。
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
位置填充
print("{0} {1}".format("hello", "world"))
关键字填充
print("{name} {age}".format(name='bruce',age=23))
通过字典的key
- d = {'name':'bruce','age':23}
- print("{student[name]} {student[age]}".format(student=d))
- print("{0[name]} {0[age]}".format(d))
对象属性填充
- class Student():
- name = 'bruce'
- age = 23
-
- print("{student.name} {student.age}".format(student=Student))
下标填充
- students = ['bruce','kevin', 'jerry']
- print("{students[0]} {students[1]} {students[2]}".format(students =students))
- print("{0[0]} {0[1]} {0[2]} {1}".format(students, 'marry'))
使用魔法参数
- args=['father']
- kwargs = {'name1': 'Bruce', 'name2': 'Jerry'}
- print('{name1} is {name2} \'s {}'.format(*args, **kwargs))
对齐
- print("{:*>10}".format(2)) #右对齐,*填充,宽度10
- print("{:*<10}".format(2)) #左对齐,*填充,宽度10
- print("{:*^10}".format(2)) #居中对齐,*填充,宽度10
b、d、o、x分别是二进制、十进制、八进制、十六进制。
- # 格式也支持二进制数字
- print("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42))
- #'int: 42; hex: 2a; oct: 52; bin: 101010'
-
- # 以0x,0o或0b作为前缀
- print("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42))
- #'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
f,%,e 浮点型,百分比,指数记法
- print("{pai:10.2f}".format(pai=3.1415926))
- print("{:10.2%}".format(0.28))
- print("{pai:10.2e}".format(pai=3.1415926))
-
- 结果:
- 3.14
- 28.00%
- 3.14e+00
'!s'它调用str(),'!r'调用repr(),'!a'调用ascii()
- print("{!r:}".format("hello"))
- print("{!s:}".format("hello"))
- print("{!a:}".format("hello"))
-
- 结果:
- 'hello'
- hello
- 'hello'
| 函数 | 功能描述 |
| name.capitalize() | 首字母大写 |
| name.count('x') | 查找某字符x在字符串内出现的次数 |
| name.find('x') | 查找字符x在字符串内第一次出现的位置,返回其下标,如果不存在返回-1 |
| name.index('x') | 查找字符x在字符串内第一次出现的位置,返回其下标,如果不存在报错 |
| name.replace(olderstr, newstr) | 查找替换,以newstr替换oldstr |
| 函数 | 功能 |
| name.strip() | 去掉字符串开头和结尾的空格和换行符 |
| name.strip('x') | 去掉开头和结尾指定字符或字符串 |
| name.lstrip('x') | 去掉字符串左边的空格和换行符或指定的字符x |
| name.rstrip('x') | 去掉字符串右边的空格和换行符或指定的字符x |
| 函数 | 功能 |
| name.isalnum() | 判断字符串是否全部为字母或数字,并且不为空 |
| name.isalpha() | 判断字符串是否全部为字母,并且不为空 |
| name.isdigit() | 判断字符串是否全部为数字,并且不为空 |
| name.isspace() | 判断字符串是否全部为空白字符, |
| name.islower() | 判断字符串是否全部为小写字母 |
| name.isupper() | 判断字符串是否全部为大写字母 |
| name.istitle() | 判断字符串是否全部首字母大写 |
- A = 'this is a good day'
- print(A.split(" "))
- 结果:
- ['this', 'is', 'a', 'good', 'day']
- A = ['this', 'is', 'a', 'good', 'day']
- print(' '.join(A))
- 结果:
- this is a good day
-
- A = 'this'
- print(' is'.join(A))
- 结果:
- t ish isi iss
会在序列的两个元素之间插入连接的字符。
+:字符串拼接
*:字符串重叠追加
- print("*2"*3)
- print("hello"+"world")
-
- 结果:
- *2*2*2
- helloworld
从0开始
- print("hello"[1])
- 结果:
- e
s[n:m:i]
n是开启的索引,m是结束的索引但是不包括该位置,i是步长。
正向下标从0开始到len(s)-1
反向下标从负的len(s)到-1
- s = "hello world"
- s1 = s[0:5:2]
- s2 =s[0:]
- s3 = s[-4:-1]
- print(s)
- print(s1)
- print(s2)
- print(s3)
- s = "hello" "world"
- print(s)
- 结果
- helloworld
str():面向用户和终端
repr():面向机器
- s = "hello world"
- print(repr(s))
- print(str(s))
-
- 结果:
- 'hello world'
- hello world
- s = ' dsds dsd '
- s1= s.encode()
- print(type(s1))
rjust()该方法返回字符串的右边的长度宽度,填充是通过使用指定的fillchar(默认为空格)。如果宽度小于len(s)返回原始字符串。
rjust(width[, fillchar])
- s = "hello"
- print(s.ljust(10,'0'))
- #!/usr/bin/python3
- intab = "aeiou"
- outtab = "12345"
- trantab = str.maketrans(intab, outtab)# 制作翻译表
- str = "this is string example....wow!!!"
- print(str.translate(trantab))
-
- 结果:
- th3s 3s str3ng 2x1mpl2....w4w!!!
bytes 只负责以字节序列的形式(二进制形式)来存储数据,至于这些数据到底表示什么内容(字符串、数字、图片、音频等),完全由程序的解析方式决定。
bytes 类型的数据非常适合在互联网上传输,可以用于网络通信编程;
不可变字节序列
1)bytes构造函数
bytes(iterable_of_ints):参数iterable_of_ints代表整数可迭代对象,包括元组,列表等,其整数不能超过255。
2)字节操作符运算
3)操作函数
bytes类型和字符串类型的操作函数几乎一样。而bytearray类型要比bytes类型多一些增删方面的函数。
和bytearray对比
bytearray是可变的字节数组
remve(value)删除列表中某个值的第一个匹配项;
pop(index =-1) 移除字节序列列表中的一个元素,默认最后一个元素。
insert(index,item)在下标为index的位置插入新的元素item。原下标位置的元素向后推移。
append(int) 尾部追加一个元素
extend(iterable_of_ints)将一个可迭代的整数结婚追加到当前bytearray
decode()方式
bytes()方式
- s = b' dsds dsd '
-
-
- s1= s.decode()
- print(type(s1))
-
- #为 bytes() 方法指定字符集
- b4 = bytes('Python31岁了', encoding='UTF-8')#UTF-8中文占3个字节
- print("b4: ", b4)
- 结果
- b4: b'Python31\xe5\xb2\x81\xe4\xba\x86'
注意:中文乱码的原因,编解码采用包不同的编码格式时。
Little Endian 和Big Endian
是计算机字节顺序的两种格式,Little Endian 把低字节存放在内存的低位;Big Endian把低字节存放在内存高位。
如果将0x1234abcd写入以0x0000开始的内存中,则

传输时如果发送端和接收端计算机的字节顺序不一致需要进行转换。
打印爱心
- print('\n'.join(
- [' '.join
- (
- [
- ('Love'
- [
- (x - y) % len('Love')
- ]
- if ((x * 0.05) **2 + (y * 0.1) **2 - 1) **3 - (x * 0.05) **2 * (y * 0.1) **3 <= 0 else ' '
- )
- for x in range(- 30, 30)
- ]
- ) for y in range(30, -30, -1)
- ]
- )
- )

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。