Python - 从文件中打印十六进制

Sha*_*hai 1 python printing hex file

我有以下代码:

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
Run Code Online (Sandbox Code Playgroud)

code1输出:

???t$?_)?½i?»±
Run Code Online (Sandbox Code Playgroud)

code2输出:

"\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1"
Run Code Online (Sandbox Code Playgroud)

我需要code2(我从文件中读取)与code1具有相同的输出.
我怎么解决这个问题?

unu*_*tbu 5

解释一系列字符,如

In [125]: list(code2[:8])
Out[125]: ['\\', 'x', 'd', '9', '\\', 'x', 'f', '6']
Run Code Online (Sandbox Code Playgroud)

因为Python是带有转义字符的字符串,例如

In [132]: list('\xd9\xf6')
Out[132]: ['\xd9', '\xf6']
Run Code Online (Sandbox Code Playgroud)

用途.decode('string_escape'):

In [122]: code2.decode('string_escape')
Out[122]: '\xd9\xf6\xd9t$\xf4_)\xc9\xbdi\xd1\xbb\x18\xb1'
Run Code Online (Sandbox Code Playgroud)

在Python3中,string_escape编解码器已被删除,因此等价物变为

import codecs
codecs.escape_decode(code2)[0]
Run Code Online (Sandbox Code Playgroud)