>> tq = "abcdef" >>> check_abcd = re.compile('^abcd') >>> if check_abcd-6ren">
gpt4 book ai didi

Python对象匹配使用字符串

转载 作者:太空宇宙 更新时间:2023-11-04 03:36:10 25 4
gpt4 key购买 nike

为什么我找不到匹配项?

>>> 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.

你可能想要匹配而不是对象。所以你可以使用

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对象匹配使用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28959371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com