Python 中文 UTF-8 编码 base64 报错

第一次用 python encode utf-8 的中文,结果发现了一个蛋疼的问题


import base64
base64.b64encode(u' 你好世界 ')

Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/base64.py", line 53, in b64encode
        encoded = binascii.b2a_base64(s)[:-1]
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

这个问题在 2008 年就提出来过,这个 Base64 的这个库的实现是按照 RFC 3548 实现的,仅按照 byte 和 ascii 字符,所以会出现这个问题。如果修复这个问题的话,就是把 unicode 字符换成 byte 就可以正常了。


_str = u"你好世界"
encoded = base64.b64encode(_str.encode('utf-8'))
print encoded
print base64.b64decode(encoded).decode('utf-8')
Licensed under CC BY-NC-SA 4.0
Built with Hugo
主题 StackJimmy 设计