Why does a new line appear at the end of my line when I finish decoding and encoding?

Here is my code:

def hex_to_base64(hex_string): clear = hex_string.decode("hex") print(clear) base64 = clear.encode("base64") print(base64) return base64 hexstring = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d" result = hex_to_base64(hexstring) # verify results if result == 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t': print("Yuuuup!!! %r" % result) else: print("Nope! %r" % result) 

The test to verify the results does not work. He prints:

 Nope! 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t\n' 

Where does the new line \ n come from? I could take it off to pass the test, but I feel it’s a hoax.

+6
source share
2 answers

Base64 encoding includes:

 >>> 'a'.encode('base64') 'YQ==\n' 

Other Base64 encoding methods also include this new line; see base64.encode() , for example:

encode() returns encoded data plus the trailing newline character ( '\n' ).

The choice seems historic; Base64 MIME transmission encoding determines that the maximum line length is used, and new lines are inserted to maintain this length, but RFC 3548 states that it should not be implemented.

Python offers both options; you can use base64.b64encode() function here:

 >>> import base64 >>> base64.b64encode('a') 'YQ==' 
+8
source

If you are looking for a way to get a coded string without a base64.b46encode newline, the base64.b46encode function will do this. Here is the difference:

 In [19]: base64.encodestring('a') Out[19]: 'YQ==\n' In [20]: base64.b64encode('a') Out[20]: 'YQ==' 
+1
source

Source: https://habr.com/ru/post/982438/


All Articles