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

问题描述 投票:0回答:2

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
python hex
2个回答
0
投票

使用字符串编码和解码功能

请参考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

0
投票

读取binary mode中的文件,以将十六进制表示形式保留为类似字节的转义十六进制字符序列。然后使用bytes.decode将类似字节的对象转换为常规str。您可以使用bytes.decode Python特定的编码作为编码类型。

unicode_escape
© www.soinside.com 2019 - 2024. All rights reserved.