>>> s='我'
>>> base64.b64encode(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python33\lib\base64.py", line 58, in b64encode
raise TypeError("expected bytes, not %s" % s.__class__.__name__)
TypeError: expected bytes, not str
出现上面的错误,就用下面这行。
>>> base64.b64encode(s.encode(encoding='utf-8'))
b'5oiR'
>>> base64.b64encode(s.encode(encoding='utf-8')).decode('utf-8')
'5oiR'
对于\u开头的字符也可以处理了。
>>> str1 = '\u4f60\u597d'
>>> str1.encode(encoding='utf-8').decode()
'你好'
>>>