Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find multiple string occurrences in Python

Tags:

python

string

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.

like image 926
taper Avatar asked Dec 06 '22 22:12

taper


2 Answers

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.

like image 159
Mark Longair Avatar answered Dec 25 '22 16:12

Mark Longair


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.

like image 22
eumiro Avatar answered Dec 25 '22 16:12

eumiro