简体   繁体   English

在Python中查找多个字符串出现

[英]find multiple string occurrences in Python

is there a way to do something like this? 有没有办法做这样的事情?

if ['hel','ell','orl'] in 'hello world' :

I want to see if all of these strings occur in the word. 我想看看是否所有这些字符串都出现在单词中。 If possible in a shorter way than completely writing a multiline foor loop. 如果可能的话,可以比完全写入多线foor环更短的方式。

You could do: 你可以这样做:

if all( x in 'hello world' for x in ['hel','ell','orl'] ):
    print "Found all of them"

The built-in functions all and any are useful for this kind of thing. 内置函数allany都适用于这种事情。

if all(substr in 'hello world' for substr in ('hel','ell','orl')):
    # all are contained

The advantage of all() is that it stops checking as soon as one substr does not match. all()的优点是,只要一个substr不匹配就会停止检查。

A multiline for loop is the correct way to proceed. 多行for循环是正确的继续进行方式。 If you don't like how it looks in your code extract it into a function and then you just have a single line function call for the same thing. 如果你不喜欢它在代码中看起来如何将它提取到一个函数中然后你只需要一个单行函数调用同样的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM