简体   繁体   中英

Extract keywords from a list then use `and`

Well I don't know how to explain this. For example I have the following code:

if 'foo' and 'bar' in 'foobar':
    print('foobar')

I want to use some keywords to check the sting, and my question is, now I'm trying to put these keywords in a list like this:

keywords = ['foo', 'bar']

But how can I use them now? If I use for to extract them like this:

for i in keywords:
    if i in 'foobar':
        print('foobar')

But this will print foobar twice.

You can use a generator expression to loop over all the keywords and check if they are all contained in 'foobar' . Using all will also allow it to short-circuit upon finding the first False .

if all(i in 'foobar' for i in keywords):
    print('foobar')

The analog to this is if you want to print if any of the keywords are found, you can use

if any(i in 'foobar' for i in keywords):
    print('foobar')

If you want to stick with a loop, you could use a for-else .

for i in keywords:
    if i not in 'foobar':
        break
else:
    print('foobar')

If any i is not in 'foobar' , the loop will exit and skip over the else section. The else if a for-else is only entered if the loop exits without break ing, which in this case will only happen if every i is in 'foobar' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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