python2与python3编码(练习)

#_author:来童星
#date:2019/12/9
import json
s='star'
a=s.encode('utf8')
print(s,type(s))# star <class 'str'>
print(a.decode('utf8'))# star

s1='星星' # unicode类型,一个汉字对应三个字节
a1=s1.encode('utf8')#按照utf编码
print(a1,type(a1))# b'xe6x98x9fxe6x98x9f' <class 'bytes'>
print(a1.decode('utf8'))# 星星
print(a1.decode('gbk'))# 鏄熸槦

b1=s1.encode('gbk')
print(b1,type(b1)) # b'xd0xc7xd0xc7' <class 'bytes'>
print(b1.decode('gbk'))# 星星
#查看字符串对应的unicode
print(json.dumps(s1)) # "u661fu661f"
# 方法二:
t='星星'
b=bytes(t,'utf8')
print(b)# b'xe6x98x9fxe6x98x9f'
s=str(b,'utf8')
print(s)# 星星

原文地址:https://www.cnblogs.com/startl/p/12012708.html