1 # bytes object 2 b = b"example" 3 4 # str object 5 s = "example" 6 7 # str to bytes 8 sb = bytes(s, encoding = "utf8") 9 10 # bytes to str 11 bs = str(b, encoding = "utf8") 12 13 # an alternative method 14 # str to bytes 15 sb2 = str.encode(s) 16 17 # bytes to str 18 bs2 = bytes.decode(b)
# bytes object
b = b"example"
# str object
s = "example"
# str to bytes
sb = bytes(s, encoding = "utf8")
# bytes to str
bs = str(b, encoding = "utf8")
# an alternative method
# str to bytes
sb2 = str.encode(s)
# bytes to str
bs2 = bytes.decode(b)
作者:zqifa
本文介绍了Python中字符串与字节对象之间的转换方法。包括使用bytes()函数将字符串转换为字节,以及使用str()函数将字节转换回字符串。此外,还提供了利用str.encode()和bytes.decode()进行转换的替代方案。
523

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



