Python - 从文件打印十六进制
我有以下代码:
code1 = ("\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1")
print code1
code2 = open("code.txt", 'rb').read()
print code2
code1 输出:
�צ�t$פ_)�½i�»±
code2 输出:
"\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1"
我需要 code2 (我从文件中读取)具有与 code1 相同的输出。
我该如何解决这个问题?
I have the following code:
code1 = ("\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1")
print code1
code2 = open("code.txt", 'rb').read()
print code2
code1 output:
�צ�t$פ_)�½i�»±
code2 output:
"\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1"
I need code2 (which I read from a file) to have the same output as code1.
How can i solve this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要解释诸如Python之类的字符序列
,将使用转义字符的字符串,例如
使用
.decode('string_escape')
:在Python3中,
string_escape
编解码器已被删除,所以等价于To interpret a sequence of characters such as
as Python would a string with escaped characters, such as
use
.decode('string_escape')
:In Python3, the
string_escape
codec has been removed, so the equivalent becomes此示例:
打印
True
。您可以使用 binascii.unhexlify 将十六进制文本表示形式转换为二进制,但首先必须从字符串中删除
\x
。编辑:我刚刚意识到双引号是您输出的一部分。本质上,您只需要传递有效的十六进制字符串,因此其他所有内容都需要被删除。在您的情况下,您需要将
code2.replace('\\x', '').strip('"')
传递给unhexlify
。您可以使用eval 可能会,但请考虑一下 Python eval() 的安全性在不受信任的字符串上?以供将来选择。
This example:
prints
True
.You can use
binascii.unhexlify
to convert hexadecimal text representation to binary, but first have to remove\x
from the string.EDIT: I've just realised that double quotes are part of your output. Essentially you need to pass just valid hex string, so everything else need to be stripped off. In your case you need to pass
code2.replace('\\x', '').strip('"')
tounhexlify
. You can useeval
and probably will, but consider this Security of Python's eval() on untrusted strings? for future choices.print eval(code2)
应该可以完成这项工作。print eval(code2)
should do the job.