python中的encode()与decode()
encode()
encode() 方法以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。
encode()方法语法:
str.encode(encoding='UTF-8',errors='strict')
- encoding – 要使用的编码,如"UTF-8"。
- errors – 设置不同错误的处理方案。默认为 ‘strict’,意为编码错误引起一个UnicodeError。 其他可能得值有 ‘ignore’,,‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 以及通过 codecs.register_error() 注册的任何值。
实例:
str_data = '大家好'
# 使用 encode() 方法对原字符串进行编码,不会直接修改原字符串,如果想修改原字符串,需要重新赋值。
byte_data = str_data.encode('utf-8')
print(byte_data) # b'\xe5\xa4\xa7\xe5\xae\xb6\xe5\xa5\xbd'
decode()
decode() 方法以 encoding 指定的编码格式解码字符串。默认编码为字符串编码。
decode()方法语法:
str.decode(encoding='UTF-8',errors='strict')
- encoding – 要使用的编码,如"UTF-8"。
- errors – 设置不同错误的处理方案。默认为 ‘strict’,意为编码错误引起一个UnicodeError。 其他可能得值有 ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 以及通过 codecs.register_error() 注册的任何值。
实例:
str_data = "大家好"
byte_data = str_data.encode('utf-8')
print(byte_data) # b'\xe5\xa4\xa7\xe5\xae\xb6\xe5\xa5\xbd'
str_new = byte_data.decode('utf-8')
print(str_new) # 大家好