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()
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.
Method 3: Check a string for a specific character using find() The string find() function returns the first occurrence of specified value.
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.
Python String startswith()The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .
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()
You could use sets:
if set('ab').intersection(set('cat')):
win()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With