字符串编码和解码
编码
字符串编码用 encode
将字符串编码成字节码(以b开头),Python中默认的编码是 utf-8
,要编程什么码,就填入对应的编码规则即可
例:
string='this is a test,这是一个测试'
print(string.encode()) # 等价于 print(string.encode('utf-8')) 以utf-8 为规则编码
print(string.encode('gbk')) # 以gbk方式编码
# print(string.encode('ascii')) # 以ASCII码方式编码,由于ASCII不支持中文,所以该语句会报错
运行结果:
b'this is a test,\xe8\xbf\x99\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xaa\xe6\xb5\x8b\xe8\xaf\x95'
b'this is a test,\xd5\xe2\xca\xc7\xd2\xbb\xb8\xf6\xb2\xe2\xca\xd4'
注意:
- Python中的utf-8编码,一个英文占一个字节,一个中文占三个字节
- ASCII码不支持对中文的编码,如果编码的字符串中有中文,会报错
解码
字符串的解码用 decode
,将以b开头的字节串,解码成对应的字符串,解码的方式要与编码的方式一致,否则会有异常
例1:
# 以utf-8方式编码
bytes_str = b'this is a test,\xe8\xbf\x99\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xaa\xe6\xb5\x8b\xe8\xaf\x95'
print(bytes_str.decode()) # 以utf-8方式解码
print(bytes_str.decode('gbk')) # 以gbk方式解码,会报错
运行结果:
this is a test,这是一个测试
如果编码缺失,也会有异常,但我们可以指定参数来忽略缺失的字节码
例2:
# 以utf-8方式编码
bytes_str = b'this is a test,\xe8\xbf\x99\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xaa\xe6\xb5\x8b\xe8'
# print(bytes_str.decode()) # 未指定忽略缺失的编码,会报错
print(bytes_str.decode(errors='ignore')) # 指定了丢弃确实的字节码,正常解码
print(bytes_str.decode(errors='replace')) # 替换了不能正确解码的内容,正常解码
运行结果:
this is a test,这是一个测 # 丢弃了
this is a test,这是一个测� # 替换了