HTF
HTF

Reputation: 7300

Convert hex string to a char in Python

Python shows a literal string value, and uses escape codes in the console:

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

How can I do the same when reading from a file?

$ 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

Upvotes: 1

Views: 988

Answers (2)

Gino Mempin
Gino Mempin

Reputation: 29711

Read the file in 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-specific encoding as the encoding type.

$ 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

Upvotes: 0

Skycc
Skycc

Reputation: 3555

using string encode and decode function

refer this for python standard encodings

for python 2

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

for python3

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

Upvotes: 1

Related Questions