美文网首页
Python中字符串与字节之间相互转换

Python中字符串与字节之间相互转换

作者: 成功在于实践 | 来源:发表于2020-09-10 21:49 被阅读0次

​> https://www.cnblogs.com/niuu/p/10106897.html

示例:


a = b"Hello, world!"   # bytes object
b = "Hello, world!"    # str object

字符串转字节 str --> bytes

print(str.encode(b))  # 默认 encoding="utf-8"

print(bytes(b, encoding="utf8"))

print(b.encode())      # 默认 encoding="utf-8"

字节转字符串 bytes --> str

print(bytes.decode(a))   # 默认encoding="utf-8"

print(str(a, encoding="utf-8"))

print(a.decode())       # 默认 encoding="utf-8"

相关文章

网友评论

      本文标题:Python中字符串与字节之间相互转换

      本文链接:https://www.haomeiwen.com/subject/ylgesktx.html