使用字符串进行Python对象匹配

使用字符串进行Python对象匹配,python,regex,string,pattern-matching,Python,Regex,String,Pattern Matching,为什么我找不到匹配的 >>> 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 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
即使变量ti和tq匹配且具有相同的引用

>>> print check_abcd.search(ti)
<_sre.SRE_Match object at 0x7ffbb05559f0>
>>> print check_abcd.search(tq)
<_sre.SRE_Match object at 0x7ffbb05559f0>
>>打印检查\u abcd.搜索(ti)
>>>打印支票搜索(tq)
为什么不匹配

`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"

尝试
如果check\u abcd.search(ti).group()==check\u abcd.search(tq).group():
将两个对象存储在单独的变量中,然后重试。然后他们的ID将不同(因为旧对象将被覆盖)嘿,vks!OP似乎会问为什么
is
操作符不工作,即使对象引用点指向同一ID。你的答案很完美!但是,在OP澄清之前,请暂停:)不!它们将被覆盖。这就是为什么连我都处于待机状态:)是的,vks和Bhargav,==在将组用作属性时工作正常。我想,即使对象引用相同的id,为什么即使我使用==或is,它也不匹配。@user2982007@BhargavRao