Matching ctrl-M character in Python
<p>I am working on an interactive program where I take some actions based on the input. For the application I want to match <code>^M</code> characters in the input stream.</p>

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

<pre><code>if hex(ord(char)) == 0xd:
    take_action()
</code></pre>

<p>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.</p>

<pre><code> 0xd
 0xd
 0xd
 0x65
 0x78
 0x69
 0x74
 0xd
 0x65
 0x78
 0x69
 0x74
 0xd
</code></pre>

<p>Could anyone tell me how to compare <code>^M</code> character and why the above does not work ?</p>

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

<pre><code>&gt;&gt;&gt; hex(13)
'0xd'
&gt;&gt;&gt; 0xd
13
&gt;&gt;&gt; hex(13) == 0xd
False
</code></pre>

<p>Remove the <code>hex()</code> call:</p>

<pre><code>if ord(char) == 0xd:
</code></pre>

<p>or just use a string literal:</p>

<pre><code>if char == '\x0d':
</code></pre>

<p>or the equivalent:</p>

<pre><code>if char == '\r':
</code></pre>

<p><code>'\r'</code> and <code>'\x0d'</code> produce the exact same character.</p>

python