Vin*_*Pai 14 python base64 encoding python-2.7 python-3.4
以下代码在python 2机器上成功运行:
base64_str = base64.encodestring('%s:%s' % (username,password)).replace('\n', '')
Run Code Online (Sandbox Code Playgroud)
我试图将它移植到Python 3,但是当我这样做时,我遇到以下错误:
>>> a = base64.encodestring('{0}:{1}'.format(username,password)).replace('\n','')
Traceback (most recent call last):
File "/auto/pysw/cel55/python/3.4.1/lib/python3.4/base64.py", line 519, in _input_type_check
m = memoryview(s)
TypeError: memoryview: str object does not have the buffer interface
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/auto/pysw/cel55/python/3.4.1/lib/python3.4/base64.py", line 548, in encodestring
return encodebytes(s)
File "/auto/pysw/cel55/python/3.4.1/lib/python3.4/base64.py", line 536, in encodebytes
_input_type_check(s)
File "/auto/pysw/cel55/python/3.4.1/lib/python3.4/base64.py", line 522, in _input_type_check
raise TypeError(msg) from err
TypeError: expected bytes-like object, not str
Run Code Online (Sandbox Code Playgroud)
我尝试搜索编码字符串使用的示例,但无法找到一个好的文档.我错过了一些明显的东西吗 我在RHEL 2.6.18-371.11.1.el5上运行它
Ana*_*mar 20
encode()在传入之前,您可以将字符串(将其转换为字节字符串)base64.encodestring.示例 -
base64_str = base64.encodestring(('%s:%s' % (username,password)).encode()).decode().replace('\n', '')
Run Code Online (Sandbox Code Playgroud)
为了扩展Anand的答案(这是非常正确的),Python 2几乎没有区分"这是一个我想要像文本一样对待的字符串"和"这是一个我想要像8位字节值序列一样对待的字符串" .Python 3牢牢地区分了两者,并且不会让你混淆它们:前者是str类型,后者是bytes类型.
当Base64对字符串进行编码时,您实际上并未将字符串视为文本,而是将其视为一系列8位字节值.这就是为什么你base64.encodestring()在Python 3中收到错误的原因:因为这是一个将字符串的字符作为8位字节处理的操作,所以你应该传递一个类型bytes的参数而不是类型的参数str.
因此,要将str对象转换为bytes对象,必须调用其encode()方法将其转换为一组8位字节值,无论您选择使用何种Unicode编码.(哪个应该是UTF-8,除非你有一个非常具体的理由选择别的东西,但这是另一个话题).