Python – Remove the new line “\n” from base64 encoded strings in Python3

base64pythonpython-3.x

I'm trying to make a HTTPS connection in Python3 and when I try to encode my username and password the base64 encodebytes method returns the encoded value with a new line character at the end "\n" and because of this I'm getting an error when I try to connect.

Is there a way to tell the base64 library not to append a new line character when encoding or what is the best way to remove this new line character? I tried using the replace method but I get the following error:

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

My code:

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

Any ideas? Thanks

Best Solution

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