print(str(b'123', encoding="utf8"))
# 123
print(bytes('123', encoding="utf8"))
# b'123'
encode 是把字符转换位 bytes 信息;decode 是把 bytes 信息转换为人可识别的字符信息
"""
bytes 与 str 间转换
b'\xe4\xbd\xa0' 8位值
你 str/unicode
python3 中表示字符序列的类型:bytes 和 str
bytes 包含原始的8位值,byte信息
str 包含Unicode字符
python2 中表示字符序列的类型:str 和 unicode
str 包含原始的8位值,byte信息
unicode 包含Unicode字符
"""
print('你'.encode('utf-8'))
# b'\xe4\xbd\xa0'
print(b'\xe4\xbd\xa0'.decode('utf-8'))
# 你
# python3
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
# python2
def to_unicode(unicode_or_str):
if isinstance(unicode_or_str, str):
value = unicode_or_str.decode('utf-8')
else:
value = unicode_or_str
return value
def to_str(unicode_or_str):
if isinstance(unicode_or_str, unicode):
value = unicode_or_str.encode('utf-8')
else:
value = unicode_or_str
return value