Skip to main content
 首页 » 编程设计

python之针对一个字符串测试多个子字符串

2025年05月04日48Terrylee

如果我有一个字符串列表:

matches = [ 'string1', 'anotherstring', 'astringystring' ] 

我还有另一个要测试的字符串:

teststring = 'thestring1' 

我想测试每个字符串,如果有任何匹配,就做一些事情。我有:

match = 0 
for matchstring in matches: 
  if matchstring in teststring: 
    match = 1 
if !match: 
  continue 

这是在一个循环中,所以如果我们没有得到匹配,我们就再绕一遍(我当然可以颠倒这个逻辑,如果匹配就做一些事情),但是代码看起来很笨拙,而不是 pythonic,如果简单的话跟随。

我在想有更好的方法来做到这一点,但我并没有像我希望的那样很好地理解 python。有没有更好的方法?

注意“重复”是相反的问题(尽管相同的答案方法是相同的)。

请您参考如下方法:

你可以使用 any这里

代码:

if any(matchstring in teststring for matchstring in matches): 
    print "Matched" 

注意事项:

  • any看到匹配项后立即退出。
  • 根据循环发生的事情是 for matchstring in matches 这里 matches 中的每个字符串都被迭代。
  • 在这里 matchstring in teststring 我们正在检查迭代字符串是否在定义的检查字符串中。
  • any 将在表达式中发现 True[match] 时立即退出。