How to check if * or * is a character in a string in Python?

I know about:

if 'a' in 'cat':
    win()

but is there a better way to find if there are either two letters in a string?

Listed below are some ways

if 'a' in 'cat' or 'd' in 'cat':
    win()

if re.search( '.*[ad].*', 'cat' ):
    win()

but is there something cleaner / faster / sharper?

how

# not actual python code
if either ['a', 'd'] in 'cat':
    win()
+4
source share
3 answers

You can use the any function :

if any(item in 'cat' for item in ['a', 'd']):  # Will evaluate to True
    win()

There is also an all function , which checks if all conditions are true :

if all(item in 'cat' for item in ['a', 'd']):  # Will evaluate to False
    win()
+11
source

You can use sets:

if set('ab').intersection(set('cat')):
    win()
+5
source

similar to selcuk's answer, except for using verisimilitude of a list with items.

if [letter for letter in ['a','d'] if letter in 'cat']:
    win()
0
source

All Articles