Remove The New Line "\n" From Base64 Encoded Strings In Python3?
Solution 1:
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
Solution 2:
Solution 3:
For Python 3 use:
binascii.b2a_base64(cipher_text, newline=False)
For Python 2 use:
binascii.b2a_base64(cipher_text)[:-1]
Solution 4:
I applied @Harsh hint and these two functions to encode and decode binary data work for my application. My requirement is to be able to use data URIs in HTML src elements and CSS @font-face statements to represent binary objects, specifically images, sounds and fonts. These functions work.
import binascii
defstring_from_binary(binary):
return binascii.b2a_base64(binary, newline=False).decode('utf-8')
defstring_to_binary(string):
return binascii.a2b_base64(string.encode('utf-8'))
Solution 5:
I concur with Mandar's observation that base64.xxxx_encode()
would produce output without line wrap \n
.
For those who want a more confident understanding than merely an observation, these are the official promise (sort of), that I can find on this topic. The 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 does not mention anything about line wrap at all.
Post a Comment for "Remove The New Line "\n" From Base64 Encoded Strings In Python3?"