python数据编码和解码

str->bytes:encode编码
bytes->str:decode解码
>>> str1 = 'hello world'
>>> str1.encode("utf-8")
b'hello world'
>>> str2 = '群主绝对是很帅的'
>>> str2 = str2.encode()
>>> str2
b'\xe7\xbe\xa4\xe4\xb8\xbb\xe7\xbb\x9d\xe5\xaf\xb9\xe6\x98\xaf\xe5\xbe\x88\xe5\xb8\x85\xe7\x9a\x84'
>>> str2.decode()
'群主绝对是很帅的'
>>> type(str2)
<class 'bytes'>
>>> type(str2.decode())
<class 'str'>
bytes.decode(encoding="utf-8", errors="strict")
str.encode(encoding="utf-8", errors="strict")
其中的encoding是指在解码编码过程中使用的编码格式,errors是指错误的处理方案。

注意:

strict:表示严格按照指定编解码方式进行编码和解码,如果编解码不成功则崩溃
ignore:表示忽略编解码不成功的字符,如果编解码不成功程序不会崩溃
发布了71 篇原创文章 · 获赞 1 · 访问量 1025

猜你喜欢

转载自blog.csdn.net/weixin_42917352/article/details/104131775