bytes转字符串方式一
b=b'\xe9\x80\x86\xe7\x81\xab'
string=str(b,'utf-8')
print(string)
# 逆火
bytes转字符串方式二
b=b'\xe9\x80\x86\xe7\x81\xab'
string=b.decode() # 第一参数默认utf8,第二参数默认strict
print(string)
#逆火
bytes转字符串方式三
b=b'\xe9\x80\x86\xe7\x81haha\xab'
string=b.decode('utf-8','ignore') # 忽略非法字符,用strict会抛出异常
print(string)
# 逆haha
bytes转字符串方式四
b=b'\xe9\x80\x86\xe7\x81haha\xab'
string=b.decode('utf-8','replace') # 用?取代非法字符
print(string)
# 逆�haha�
字符串转bytes方式一
str1='逆火'
b=bytes(str1, encoding='utf-8')
print(b)
# b'\xe9\x80\x86\xe7\x81\xab'
字符串转bytes方式二
b=str1.encode('utf-8')
print(b)
# b'\xe9\x80\x86\xe7\x81\xab'
本文详细介绍了四种将bytes类型转换为字符串的方法,包括使用str()函数、decode()方法的不同参数设置,以及两种将字符串转换为bytes的方式。这些方法在处理编码问题时特别有用,如utf-8编码的处理。
1692

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



