admin管理员组文章数量:1611397
文章目录
- 前言
- 方法一
- 方法二
- 参考链接
前言
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
版权声明:本文标题:‘utf-8‘ codec can‘t decode byte 0x.. in position .: invalid start byte 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1728604037a1165225.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论