I have the following code:
check = "red" in string_to_explore
How can I replicate it for multiple substrings?
I tried with:
check = "red|blue" in string_to_explore
but doesn't seem to work.
Thanks in advance,
Python str methods doesn't accept regex pattern, for that use re
module:
import re
text = "foo foo blue foo"
pattern = re.compile(r"red|blue")
check = bool(pattern.search(text))
print(check) # True
You can simply do it using a list containing your substrings and a for loop to check if the strings in the list are present. Here's an example codes:
main_string = "This is a string containing red and blue colors."
substrings = ["red", "blue"]
check = any(substring in main_string for substring in substrings)
print(check)
You can use a list comprehension with any.
string_to_explore="red my friend"
strings="red|blue".split("|")
check = any([x in string_to_explore for x in strings])
print(check)
string_to_explore1="blue my friend"
check1 = any([x in string_to_explore1 for x in strings])
print(check1)
string_to_explore2 = "nothing my friend"
check2 = any([x in string_to_explore2 for x in strings])
print(check2)
# True
# True
# False
any
works just fine with.
any
is done with it; and second, it defeats the purpose of any
's ability to short-circuit when a True
is found, forcing all elements of the comprehension to be calculated