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

桃扇骨 2024-04-18 14:13 148阅读 0赞
  1. a = b"Hello, world!" # bytes object
  2. b = "Hello, world!" # str object

字符串转字节 str —> bytes

  1. # 字符串转字节 str --> bytes
  2. print(str.encode(b)) # 默认 encoding="utf-8"
  3. print(bytes(b, encoding="utf8"))
  4. print(b.encode()) # 默认 encoding="utf-8"

字节转字符串 bytes —> str

  1. ​# 字节转字符串 bytes --> str
  2. print(bytes.decode(a)) # 默认encoding="utf-8"
  3. print(str(a, encoding="utf-8"))
  4. print(a.decode()) # 默认 encoding="utf-8"

发表评论

表情:
评论列表 (有 0 条评论,148人围观)

还没有评论,来说两句吧...

相关阅读