marke
marke

Reputation: 1074

Why python interprets hex strings in different way?

I have recently had to do something with characters that were written with \xAB escape syntax, and noticed that there is a different behavior for different characters:

>>>'\x61'
'a'
>>>'\x10'
'\x10'
>>>print('\x61')
a
>>>print('\x10')


My question is: why >>> '\x10' doesn't yield ''?

Upvotes: 0

Views: 54

Answers (1)

chepner
chepner

Reputation: 531400

They are interpreted the same. The difference is in the representation defined by str.__repr__, which prefers to use printable ASCII characters where possible.

print(x) uses x.__str__, not x.__repr__, which simply returns the string itself, and then writes that string to the terminal, at which point it is up to the terminal, not Python, to decide how to display the result.

\x10, in particular, indicates the control character DLE (Data Link Escape), which doesn't have any particular meaning to the terminal, so it is typically left undisplayed or, in some cases, shown with some generic placeholder like ?.

Upvotes: 4

Related Questions