简体   繁体   English

在python中将字节字符串转换为字符串

[英]Convert byte string to string in python

I'm using PyCrypto, and python 2.7.3.我正在使用 PyCrypto 和 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.我试图在散列前添加一个常规字符串以创建链式散列,但为了保持格式一致,我需要“打印”形式的字符串 s 而不是二进制形式。 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.在交互式解释器中输入s时,您看到的是字符串的表示形式 You shouldn't be concerned about what this looks like – the actual string contents is what gets printed when you use print.您不应该关心这看起来像什么——实际的字符串内容是您使用 print 时打印的内容。 There is no way to "convert" the string to what is printed when using print since the string already has that contents.使用print时无法将字符串“转换”为打印的内容,因为字符串已经包含该内容。

Try using .hexdigest() instead.尝试使用.hexdigest()代替。 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:不确定我是否理解正确,但如果你的意思是十六进制表示,你可以查看 std-lib 的binascii -module:

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:如果你只是想在 s 前面加上一个字符串,就像 Sven Marnach 说的那样,不要打扰打印的内容,只需将 s 附加到你的前缀,例如:

prefix = 'username:'
combined_string = prefix + s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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