本文介绍了Python对象匹配使用字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我找不到匹配项?
>>>ti = "abcd">>>tq = "abcdef">>>check_abcd = re.compile('^abcd')>>>如果 check_abcd.search(ti) 是 check_abcd.search(tq):...打印匹配"... 别的:...打印不匹配"...不匹配即使变量 ti 和 tq 匹配并具有相同的引用
>>>打印 check_abcd.search(ti)<_sre.SRE_Match 对象在 0x7ffbb05559f0>>>>打印 check_abcd.search(tq)<_sre.SRE_Match 对象在 0x7ffbb05559f0>为什么不匹配?
解决方案
`is` 是身份测试,== 是平等测试.如果两个变量指向同一个对象,is 将返回 True,如果变量引用的对象相等,则返回 ==.
您可能想要匹配 values
而不是 objects
.所以你可以使用
ti = "abcd"tq = "abcdef"check_abcd = re.compile('^abcd')如果 check_abcd.search(ti).group(0) == check_abcd.search(tq).group(0):打印匹配"别的:打印不匹配"
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?
解决方案
`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"
这篇关于Python对象匹配使用字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!