Skip to main content
 首页 » 编程设计

Python对象匹配使用字符串

2024年10月25日23TianFang

为什么我找不到匹配项?

>>> ti = "abcd" 
>>> tq = "abcdef" 
>>> check_abcd = re.compile('^abcd') 
>>> if check_abcd.search(ti) is check_abcd.search(tq): 
...     print "Matching" 
... else: 
...     print "not matching" 
... 
not matching 

尽管变量 ti 和 tq​​ 都匹配并且具有相同的引用

>>> print check_abcd.search(ti) 
<_sre.SRE_Match object at 0x7ffbb05559f0> 
>>> print check_abcd.search(tq) 
<_sre.SRE_Match object at 0x7ffbb05559f0> 

为什么不匹配?

请您参考如下方法:

`is` is identity testing, == is equality testing.  
 is will return True if two variables point to the same object, == if the objects referred to by the variables are equal. 

你可能想要匹配值而不是对象。所以你可以使用

ti = "abcd" 
tq = "abcdef" 
check_abcd = re.compile('^abcd') 
 
if check_abcd.search(ti).group(0) == check_abcd.search(tq).group(0): 
    print "Matching" 
else: 
    print "not matching"