Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'[email protected]:passWORD' auth_base64 = base64.encodebytes(auth) auth_base64 = auth_base64.replace('\n', '') 

Any ideas? Thanks

like image 565
Mo. Avatar asked Jun 04 '15 14:06

Mo.


2 Answers

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

In [11]: auth = b'[email protected]: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

like image 150
Mandar Vaze Avatar answered Sep 30 '22 07:09

Mandar Vaze


Following code would work

auth_base64 = auth_base64.decode('utf-8').replace('\n', '') 
like image 25
Sarit Adhikari Avatar answered Sep 30 '22 09:09

Sarit Adhikari