问题
Why i am not able to find the match?
>>> 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
Eventhough both variables ti and tq are matching and having same reference
>>> print check_abcd.search(ti)
<_sre.SRE_Match object at 0x7ffbb05559f0>
>>> print check_abcd.search(tq)
<_sre.SRE_Match object at 0x7ffbb05559f0>
Why it is not matching?
回答1:
`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.
You probably want to match values and not objects.So you can use
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"
来源:https://stackoverflow.com/questions/28959371/python-object-matching-using-string