Python 使用字符串匹配对象

Python object matching using string

为什么我找不到匹配项?

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

您可能想要匹配 values 而不是 objects。因此您可以使用

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"