python 编码问题

#python3,str和bytes类型相互转换工具类
#file:python3_endecode_helper.py
def to_str(bytes_or_str):
if isinstance(bytes_or_str,bytes):
value = bytes_or_str.decode('UTF-8')
else:
value = bytes_or_str
return value

def to_bytes(bytes_or_str):
if isinstance(bytes_or_str,str):
value = bytes_or_str.encode('UTF-8')
else:
value = bytes_or_str
return value

if __name__=='__main__':
str_string = u'中国'
value = to_bytes(str_string)
print(type(value)) #<class 'bytes'>
value = to_str(value)
print(type(value)) #<class 'str'>

原文地址:https://www.cnblogs.com/bobo200/p/11770440.html