看廖雪峰老师python博客笔记——字符串和编码

1. 在计算机内存中,统一使用Unicode编码,当需要保存到硬盘或者需要传输的时候,就转换为UTF-8编码;
浏览网页的时候,服务器会把动态生成的Unicode内容转换为UTF-8再传输到浏览器。
2. 最新的Python 3版本中,字符串是以Unicode编码的,也就是说,Python的字符串支持多语言;ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符。
3. (1)要注意区分'ABC'和b'ABC'(python对bytes类型的数据表示),前者是str,后者虽然内容显示得和前者一样,但bytes的每个字符都只占用一个字节。如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法:
>>> b'ABC'.decode('ascii')
与之相对的是encode()方法

(2)如果bytes中只有一小部分无效的字节,可以传入errors='ignore'忽略错误的字节:

>>> b'\xe4\xb8\xad\xff'.decode('utf-8', errors='ignore')

'中'
4. len()函数计算的是str的字符数
5. 格式化:
(1)>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'
(2)format():
>>> 'Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125)
'Hello, 小明, 成绩提升了 17.1%'
>>> "Hello, {} and {}!".format("John", "Mary")
>>> "Hello, {boy} and {girl}!".format(boy="John", girl="Mary")
>>>"My car is {0.color}.".format(black_car)
>>>"The first student is {student[0]}.".format(student=stu_list)
>>>"John is {d[john]} years old.".format(d=age_dict)
//所以这是一种更加像函数调用的格式化方法
发布了19 篇原创文章 · 获赞 2 · 访问量 5177

猜你喜欢

转载自blog.csdn.net/gunjiu4462/article/details/79863730