python基础2-字符串与字节
字符串与字节的转换
字符串转换成字节的函数 encode()
字节转换成字符串的函数 dencode()
1 字符串字符串转换成字节
print('张'.encode('utf8')) >>b'\xe5\xbc\xa0' print('张'.encode('ascii')) >>Traceback (most recent call last): >>File "D:/pachong/1.py", line 3, in <module>>>UnicodeEncodeError: 'ascii' codec can't encode character '\u5f20' in position 0: ordinal not in range(128) # 报错了,因为中文不支持ASCII编码转换,中文要使用utf8编码 print('A'.encode('ascii')) >>b'A' # 英文则支持ASCII编码
2 对比中文和英文在utf8编码时占用的字节数
print(len('张'.encode('utf8'))) print(len('A'.encode('utf8'))) # 结果 3 1
由此可知,1个中文字符经过utf8编码后为3字节,1个英文字符经过utf8编码后为1字节
3 python文件开头要写清楚编码
#!/usr/bin/env python3 # -*- coding: utf-8 -*-
编辑器保存格式为utf8 with BOM

浙公网安备 33010602011771号