字符串与编码
在最新的Python 3版本中,字符串是以Unicode编码的。
Python提供ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符:
>>> ord('A')
65
>>> ord('中')
20013
>>> chr(66)
'B'
Python对bytes类型的数据用带b前缀的单引号或双引号表示:
x = b'ABC'
以Unicode表示的str通过encode()方法可以编码为指定的bytes,例如:
>>> 'ABC'.encode('ascii')
b'ABC'
>>> '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
要把bytes变为str,就需要用decode()方法:
>>> b'ABC'.decode('ascii')
'ABC'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'中文'
格式化
%运算符就是用来格式化字符串的。在字符串内部,%s表示用字符串替换,%d表示用整数替换
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'
使用字符串的format()方法,它会用传入的参数依次替换字符串内的占位符{0}、{1}……
>>> 'hello,{0} 收入增加{1:.1f}%'.format('小王',12.5)
'hello,小王 收入增加12.5%'
使用以f开头的字符串,称之为f-string,它和普通字符串不同之处在于,字符串如果包含{xxx},就会以对应的变量替换:
>>> r=2.5 >>> s=3.14*r**2 >>> print(f'The area of a circle with radius {r} is {s:.2f}') The area of a circle with radius 2.5 is 19.62
立志如山 静心求实
浙公网安备 33010602011771号