python - base64.encodestring 在 python 3 中失败

标签 python python-2.7 encoding base64 python-3.4

以下代码在 python 2 机器上成功运行:

base64_str = base64.encodestring('%s:%s' % (username,password)).replace('\n', '')

我正在尝试将它移植到 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

我尝试搜索 encodestring 用法的示例,但找不到合适的文档。我错过了一些明显的东西吗?我在 RHEL 2.6.18-371.11.1.el5 上运行这个

最佳答案

您可以encode() 字符串(将其转换为字节字符串),然后再将其传递给base64.encodestring。示例 -

base64_str = base64.encodestring(('%s:%s' % (username,password)).encode()).decode().strip()

关于python - base64.encodestring 在 python 3 中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31144988/

相关文章:

python - 根据其他数据框中的索引列表将新列添加到其他数据框中的数据框中

Python 2.7 类属性奇怪的行为

python:dict上json.dumps的行为

python - 何时以及如何使用 Python 的 RLock

python - 使用 Python C 扩展时如何修复 'UnicodeDecodeError: ' utf- 8' codec can' t decode byte'?

python - 合并 Pandas 中的两个数据框

python - 如何在python中获取两个日期之间的所有日期(月、日和年)?

python - Geoplot 不会绘制 geopandas 对象

string - Node.js 无法解码字符串..字符乱码(问号)

javascript - Javascript 中的奇怪字符导致它无法加载