问题描述:

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:

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'm getting from the program is as follows:

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'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 DesiredResult?

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
相关阅读:
Top