admin管理员组

文章数量:1612099

文章目录

  • 前言
  • 方法一
  • 方法二
  • 参考链接

前言

python中,string和bytes互转的时候,经常会遇到这个问题。常用的解决方法有两种

方法一

在获取bytes的时候就指明使用的字符集。这里拿utf-8举例:

with open('1.txt', 'r+', encoding='utf8') as f:
      content = f.read()

甚至是在写入的时候就指明字符集:

with open('1.txt', 'w+', encoding='utf8') as f:
      f.write(b'pandora')

对这样读出的bytes流使用decode('utf-8')就不会出错了。

方法二

没法像上面这样做到控制怎么办?比如生成的随机数密钥。或者嫌麻烦,有没有更好的方法?

办法很简单,使用base64之类的编码先将bytes流转为常见的文本字符对应的bytes流,然后再对处理后的bytes流使用decode('utf-8')之类的办法就没问题了。

这里用base64库提供的base64.b64encode()举例:

import base64
byte_s = b'\xbc#\x02\t\x1f2\xf4\xff'
# str_s = byte_str.decode('utf-8') # 会报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbc in position 0: invalid start byte
base64_bytes = base64.b64encode(byte_s)
str_s = base64_bytes.decode('utf-8')
print(str_s)

复原的时候倒序进行一遍就行:

base64_bytes = str_s.encode('utf-8')
byte_s = base64.b64decode(base64_bytes)
print(byte_s)

参考链接

  • PyCryptodome - document
  • Python utf-8与byte的解码问题 - CSDN

本文标签: DecodeCodecUTFbytestart