Python code working differently after a print statement
<p>I'm trying to use regex to search the keys in a dict and return the matches.  The following code is simplified from the real code but shows the problem.</p>

<pre><code>#!/bin/python

# Import standard Python modules
import os, sys, string, pdb, re

key=""
pat=""

steps = {"pcb":"xxx","aoi":"xxx","pcb-pec":"xxx","pcb_1":"xxx"}
pat = "pcb"

print"***Search the dict***"
for key in steps:
    print re.search(key,pat)

print"***Search the key***"
key = "pcb-pec"
pat = "pcb"
print re.search(key,pat)

print"***Search the key after printing it***"
key = "pcb-pec"
pat = "pcb"
print 'key:' + key+ ' ,pattern:' + pat
print re.search(pat,key)

exit()
</code></pre>

<p>And the output is this:</p>

<pre><code>***Search the dict***
&lt;_sre.SRE_Match object at 0x00000000031FBC60&gt;
None
None
None
***Search the key***
None
***Search the key after printing it***
key:pcb-pec ,pattern:pcb
&lt;_sre.SRE_Match object at 0x00000000031FBC60&gt;
</code></pre>

<p>I don't understand why the pattern isn't found on the 3rd and 4th keys.</p>

<p>I don't understand why the pattern isn't found in the second test either.</p>

<p>I REALLY don't understand why it is found in the third test which is the same as the second, but with a print statement.</p>

<p>This is my first post, but I've learned a lot by searching and reading here.  Many thanks to you all.</p>

<p>You change the order of parameters in your last case. You have them out of order the first couple of times, and in the correct order the last time</p>

<pre><code>re.search(pat,key)
</code></pre>

<p>is the correct order.</p>

<p>In the loop, you're getting a match the one time the pattern and the string happen to be the same.</p>

python regex python-2.7