Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if *either* character is in a string in Python? [closed]

Tags:

python

string

I know about:

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

but is there a better way to finding if either of two letters exist in a string?

The following are some ways,

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

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

but is there something cleaner/faster/clearer?

Like,

# not actual python code
if either ['a', 'd'] in 'cat':
    win()
like image 351
user2738698 Avatar asked Mar 26 '15 15:03

user2738698


People also ask

What does * do to strings in Python?

Concatenation of Two or More Strings The + operator does this in Python. Simply writing two string literals together also concatenates them. The * operator can be used to repeat the string for a given number of times.

How do I check if a string contains a specific character in Python?

Method 3: Check a string for a specific character using find() The string find() function returns the first occurrence of specified value.

What does * string mean in Python?

String is a collection of alphabets, words or other characters. It is one of the primitive data structures and are the building blocks for data manipulation. Python has a built-in string class named str . Python strings are "immutable" which means they cannot be changed after they are created.

How do you check if a string starts with a special character in Python?

Python String startswith()The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .


2 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 the all() function which will check if all conditions are true:

if all(item in 'cat' for item in ['a', 'd']):  # Will evaluate to False
    win()
like image 168
Selcuk Avatar answered Oct 02 '22 13:10

Selcuk


You could use sets:

if set('ab').intersection(set('cat')):
    win()
like image 25
Lee Avatar answered Oct 02 '22 12:10

Lee