Python object matching using string

早过忘川 提交于 2019-12-24 02:17:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!