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
本文详细介绍了Python3中字符串与字节串之间的转换。通过`encode`和`decode`方法,可以实现UTF-8编码下的转换。同时,提供了在Python2下进行类似操作的函数。理解这些概念对于处理字符编码问题至关重要。
531

被折叠的 条评论
为什么被折叠?



