I'm trying to write a short program in Python to convert a string from hex into bytes, and then from bytes into base64. I've got a base string in hexadecimal, and the equivalent of the string in base64. The program looks like this:
basecode = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
DesiredResult = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"
e = codecs.decode(basecode, 'hex')
y = codecs.encode(e, 'base64')
z = bytes.decode(y, 'utf-8')
if y == DesiredResult:
The output I'm getting from the program is as follows:
b"I'm killing your brain like a poisonous mushroom"
As I'm sure you can imagine, this is frustrating, because it means that while I've come close, I haven't actually done what I set out to do.
So, how can I modify this program to make sure that the output of my conversion is exactly the same as the variable
I know it has to do with the
\n that appears in the conversion, but I don't know how it gets there, and I don't know how to get rid of it.
Any and all suggestions greatly appreciated.
The base64 codec always adds a
\n byte at the end.
Convert operand to MIME base64 (the result always includes a trailing '\n')
To strip the last
\n byte, use the Python slicing operator like this:
>>> y 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t\n' >>> DesiredResult 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t' >>> y[:-1] 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t' >>> y[:-1] == DesiredResult True