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

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


Instead of encodestring consider using b64encode. Later does not add \n characters. e.g.

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=='

It produces identical encoded string except the \n


Following code would work

auth_base64 = auth_base64.decode('utf-8').replace('\n', '')


For Python 3 use:

binascii.b2a_base64(cipher_text, newline=False)

For Python 2 use:

binascii.b2a_base64(cipher_text)[:-1]