python - 从 Python3 中的 base64 编码字符串中删除新行 "\n"?

标签 python python-3.x base64

我正在尝试在 Python3 中建立 HTTPS 连接,当我尝试对我的用户名和密码进行编码时,base64 encodebytes 方法会返回带有新行的编码值末尾的字符“\n”,因此,当我尝试连接时出现错误。

有没有办法告诉 base64 库在编码时不要附加换行符,或者删除这个换行符的最佳方法是什么?我尝试使用 replace 方法,但出现以下错误:

Traceback (most recent call last):
  File "data_consumer.py", line 33, in <module>
    auth_base64 = auth_base64.replace('\n', '')
TypeError: expected bytes, bytearray or buffer compatible object

我的代码:

auth = b'username@domain.com:passWORD'
auth_base64 = base64.encodebytes(auth)
auth_base64 = auth_base64.replace('\n', '')

有什么想法吗?谢谢

最佳答案

考虑使用 b64encode 而不是 encodestring。稍后不添加 \n 字符。例如

In [11]: auth = b'username@domain.com:passWORD'

In [12]: base64.encodestring(auth)
Out[12]: b'dXNlcm5hbWVAZG9tYWluLmNvbTpwYXNzV09SRA==\n'

In [13]: base64.b64encode(auth)
Out[13]: b'dXNlcm5hbWVAZG9tYWluLmNvbTpwYXNzV09SRA=='

它产生相同的编码字符串,除了 \n

关于python - 从 Python3 中的 base64 编码字符串中删除新行 "\n"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30647219/

相关文章:

python - 在python中追加错误

python - 如何从 numpy 数组列表中删除重复元素?

python - 如何使用 while 循环从列表中的每个整数中减去最小的数字?

python - 在 flask 中运行破折号应用程序

python - 如何从多个字符串中删除某些字符?

python - unicodedata.decomposition() 与 unicodedata.normalize(NFD/NFKD)?

email - MIME 电子邮件的 Base64 解码不起作用(GMail API)

python - 在没有多重索引的情况下分割 Pandas 系列

php - WS-Security php 中 PasswordDigest 的工作算法

python - 如何获取 PIL 图像作为 Base64 编码的字符串