简体   繁体   English

打印语句后,Python代码的工作方式有所不同

[英]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. re.search的签名(给定为re.search(pattern, string, flags=0) )首先采用模式,然后采用字符串。

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. 在循环中,模式和字符串恰好相同的一次就得到了匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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