简体   繁体   中英

Python code working differently after a print statement

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.

#!/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()

And the output is this:

***Search the dict***
<_sre.SRE_Match object at 0x00000000031FBC60>
None
None
None
***Search the key***
None
***Search the key after printing it***
key:pcb-pec ,pattern:pcb
<_sre.SRE_Match object at 0x00000000031FBC60>

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

I don't understand why the pattern isn't found in the second test either.

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.

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

The signature of re.search (given as re.search(pattern, string, flags=0) ) takes the pattern first, then the string.

You should swap the order of the parameters:

re.search(pat, key)
#         ^^^^^^^^

And then the other keys will work:

In [27]: pat = "pcb"

In [28]: key = "pcb-pec"

In [29]: re.search(key,pat) # wrong order

In [30]: re.search(pat,key) # right order
Out[30]: <_sre.SRE_Match object; span=(0, 3), match='pcb'>

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

re.search(pat,key)

is the correct order.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM