简体   繁体   中英

Convert byte string to string in python

I'm using PyCrypto, and python 2.7.3. I'm attempting to prepend a regular string to the hash to create a chained hash, but to keep formats consistent, I need the string s in the 'printed' form instead of the binary form. Is there any way to convert the binary string into a manipulable "normal" string?

from Crypto.Hash import SHA256
h = SHA256.new()
s = h.digest() #return binary "non-printable" digest

s
>>>"\xe3\xb0\xc4B\x98\xfc\x1c\x14\x9a\xfb\xf4\xc8\x99o\xb9$'\xaeA\xe4d\x9b\x93L\xa4\x95\x99\x1bxR\xb8U"
print(s)
>>> ã°ÄB˜üšûôÈ™o¹$'®Aäd›“L¤•™xR¸U

Thanks for any help

What you see when entering s in the interactive interpreter is the representation of the string. You shouldn't be concerned about what this looks like – the actual string contents is what gets printed when you use print. There is no way to "convert" the string to what is printed when using print since the string already has that contents.

Try using .hexdigest() instead. You will get a string representation as hex digits.

Not sure if i got you right, but if you mean a hex-representation you may look into the binascii -module of the std-lib:

from binascii import b2a_hex #bin to ascii: hex-format
print b2a_hex(s)
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'

if you just want to prepend a string to s, it's like Sven Marnach said, don't bother what is printed, just append s to your prefix, like:

prefix = 'username:'
combined_string = prefix + s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM