Use any for this:
>>> s = 'blahblahAA'
>>> any(x not in s for x in ('AA', 'BB', 'CC'))
True
Your current code is equivalent to:
if ('AA') or ('BB') or ('CC' not in string)
As 'AA' is True(bool('AA') is True), so this always evaluates to True.
Use any for this:
>>> s = 'blahblahAA'
>>> any(x not in s for x in ('AA', 'BB', 'CC'))
True
Your current code is equivalent to:
if ('AA') or ('BB') or ('CC' not in string)
As 'AA' is True(bool('AA') is True), so this always evaluates to True.
You should use an and instead of an or statement. Right now, you always print 'Nope' if one of the substrings is not in your string.
In the example given above, you still print 'Nope' because 'BB' and 'CC' are not in the string and the whole expression evaluates to true.
Your code could look like this:
if ('AA' not in string) and ('BB' not in string) and ('CC' not in string):
print 'Nope'
python - Check if multiple strings exist in another string - Stack Overflow
python - Efficient multiple substrings search - Software Engineering Stack Exchange
How to check if any element in a list contains a substring
Checking whether multiple substrings are within a string?
Videos
For example I am looking for a shorter and cleaner way to do the following:
f = "robot_F.txt"
if "_F_" in f or "_F." in f or "_R_” in f or "_R." in f:
print (" Success")Something like:
if ("_F_", "_F.", "_R_","_R.") in f:
print(" Success")You can use any:
a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]
if any(x in a_string for x in matches):
Similarly to check if all the strings from the list are found, use all instead of any.
any() is by far the best approach if all you want is True or False, but if you want to know specifically which string/strings match, you can use a couple things.
If you want the first match (with False as a default):
match = next((x for x in a if x in a_string), False)
If you want to get all matches (including duplicates):
matches = [x for x in a if x in a_string]
If you want to get all non-duplicate matches (disregarding order):
matches = {x for x in a if x in a_string}
If you want to get all non-duplicate matches in the right order:
matches = []
for x in a:
if x in a_string and x not in matches:
matches.append(x)