What happens to the output of this conversion, and why is it not the way I believe it is?
I am trying to write a short program in Python to convert a string from hex to bytes and then from byte to base64. I have a base string in hex and a base64 string equivalent. The program looks like this:
import codecs
basecode = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
DesiredResult = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"
e = codecs.decode(basecode, 'hex')
print(e)
y = codecs.encode(e, 'base64')
print(y)
z = bytes.decode(y, 'utf-8')
print(z)
print(DesiredResult)
if y == DesiredResult:
print("Success!")
The output I get from the program looks like this:
b"I'm killing your brain like a poisonous mushroom"
b'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t\n'
SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t
SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t
As I'm sure you can imagine, this is frustrating because it means that while I'm getting closer, I haven't actually done what I set out to do.
So how can I modify this program to make sure the output of my transformation is exactly the same as the variable DesiredResult
?
I know what it has to do with \n
which appears in the transformation, but I don't know how it got there, and I don't know how to get rid of it.
All suggestions and suggestions are greatly appreciated.
source to share
base64 codec always adds a byte \n
at the end.
Convert operand to MIME64 base (result always includes trailing "\ n")
To remove the last \n
byte, use the Python cut operator like this:
>>> y
'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t\n'
>>> DesiredResult
'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
>>> y[:-1]
'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t'
>>> y[:-1] == DesiredResult
True
source to share