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'>

posted on 2019-10-31 12:01  jenny_200  阅读(156)  评论(0编辑  收藏  举报

导航