Sharad Sharad - 3 months ago 51
Python Question

Matching ctrl-M character in Python

I am working on an interactive program where I take some actions based on the input. For the application I want to match

^M
characters in the input stream.

To do this I found the ASCII equivalent of
^M
which is
0xd
and converted the input character to ascii using
hex(ord(char))
and compared the two.

if hex(ord(char)) == 0xd:
take_action()


But this condition never evaluates to true. To see if I am using the correct ascii values I wrote the input I am sending to a file.

0xd
0xd
0xd
0x65
0x78
0x69
0x74
0xd
0x65
0x78
0x69
0x74
0xd


Could anyone tell me how to compare
^M
character and why the above does not work ?

Answer

0xd is an integer literal (it produces the value 13), but hex() returns a string. '0xd' may look like 0xd, but are not equal:

>>> hex(13)
'0xd'
>>> 0xd
13
>>> hex(13) == 0xd
False

Remove the hex() call:

if ord(char) == 0xd:

or just use a string literal:

if char == '\x0d':

or the equivalent:

if char == '\r':

'\r' and '\x0d' produce the exact same character.