Python3笔记023 - 5.2 字符串编码转换

5.2 字符串编码转换

5.2.1 encode()方法以 encoding 指定的编码格式编码字符串

str.encode([encoding="utf-8"][errors="strict"])
str1 = "星期一星期二星期三星期四星期五星期六星期日"
byte1 = str1.encode('UTF-8')
print(byte1)
output:
b'\xe6\x98\x9f\xe6\x9c\x9f\xe4\xb8\x80\xe6\x98\x9f\xe6\x9c\x9f\xe4\xba\x8c\xe6\x98\x9f\xe6\x9c\x9f\xe4\xb8\x89\xe6\x98\x9f\xe6\x9c\x9f\xe5\x9b\x9b\xe6\x98\x9f\xe6\x9c\x9f\xe4\xba\x94\xe6\x98\x9f\xe6\x9c\x9f\xe5\x85\xad\xe6\x98\x9f\xe6\x9c\x9f\xe6\x97\xa5'

5.2.2 decode()方法以 encoding 指定的编码格式解码字符串

bytes.decode([encoding="utf-8"][,errors="strict"])
byte1 = b'\xe6\x98\x9f\xe6\x9c\x9f\xe4\xb8\x80\xe6\x98\x9f\xe6\x9c\x9f\xe4\xba\x8c\xe6\x98\x9f\xe6\x9c\x9f\xe4\xb8\x89\xe6\x98\x9f\xe6\x9c\x9f\xe5\x9b\x9b\xe6\x98\x9f\xe6\x9c\x9f\xe4\xba\x94\xe6\x98\x9f\xe6\x9c\x9f\xe5\x85\xad\xe6\x98\x9f\xe6\x9c\x9f\xe6\x97\xa5'
str1 = byte1.decode('GBK')
print(str1)
output:
星期一星期二星期三星期四星期五星期六星期日
posted @ 2020-07-07 06:41  测试工匠麻辣烫  阅读(126)  评论(0编辑  收藏  举报