为什么我找不到比赛?
>>> 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"