将十六进制字符串转换为 Python 中的字符

Convert hex string to a char in Python

Python 显示文字字符串值,并在控制台中使用转义码:

>>> x = '\x74\x65\x73\x74'
>>> x
'test'
>>> print(x)
test

如何在读取文件时执行相同的操作?

$ cat test.txt 
\x74\x65\x73\x74

$ cat test.py 
with open('test.txt') as fd:
    for line in fd:
        line = line.strip()
        print(line)

$ python3 test.py
\x74\x65\x73\x74

使用字符串编码和解码函数

参考 this python 标准编码

对于 python 2

line = "\x74\x65\x73\x74"
line = line.decode('string_escape')
# test

对于 python3

line = "\x74\x65\x73\x74"
line = line.encode('utf-8').decode('unicode_escape')
# test

binary mode to preserve the hex representation into a bytes-like sequence of escaped hex characters. Then use bytes.decode to convert from a bytes-like object to a regular str. You can use the unicode_escape读取文件Python-特定编码作为编码类型。

$ cat test.txt
\x74\x65\x73\x74

$ cat test.py
with open('test.txt', "rb") as fd:
    for line in fd:
        print(line)
        print(line.decode("unicode_escape"))

$ python3 test.py
b'\x74\x65\x73\x74\n'
test