从 Python3 中的 base64 编码字符串中删除新行“\n”?

Remove the new line "\n" from base64 encoded strings in Python3?

我正在尝试在 Python3 中建立 HTTPS 连接,当我尝试对我的用户名和密码进行编码时 base64 encodebytes 方法 returns 编码值在“\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', '')

有什么想法吗?谢谢

以下代码可以工作

auth_base64 = auth_base64.decode('utf-8').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

之外,它生成相同的编码字符串

我同意 base64.xxxx_encode() 会产生没有换行的输出 \n

对于那些想要更自信的理解而不仅仅是观察的人来说,这些是我可以找到的关于这个主题的官方承诺(某种程度上)。 Python 3 documentation does mention base64.encode(...) would add newlines after every 76 bytes of output. Comparing to that, all other *_encode(...) functions do not mention their linewrap behavior at all, which can argurably be considered as "no line wrap behavior". For what it's worth, the Python 2 documentation 根本没有提到换行。

对于 Python 3 使用:

binascii.b2a_base64(cipher_text, newline=False)

对于 Python 2 使用:

binascii.b2a_base64(cipher_text)[:-1]

我应用@Harsh 提示和这两个函数来为我的应用程序编码和解码二进制数据。我的要求是能够在 HTML src 元素和 CSS @font-face 语句中使用数据 URI 来表示二进制对象,特别是图像、声音和字体。这些功能有效。

import binascii

def string_from_binary(binary): 
    return binascii.b2a_base64(binary, newline=False).decode('utf-8')

def string_to_binary(string): 
    return binascii.a2b_base64(string.encode('utf-8'))