0

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,

0

3 Answers 3

3

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
1

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) 
0

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
3
  • 1
    The list is completely unnecessary overhead, you can just remove the square brackets, that'll create a generator comprehension which any works just fine with.
    – Masklinn
    Commented May 17, 2024 at 12:16
  • 1
    The list comprehension is unnecessary overhead in two ways: first, it forces the creation of the list which is discarded after 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
    – pho
    Commented May 17, 2024 at 12:22
  • @pho Yes, you are right, mainly about the short-circuit part. I think the list with a couple of True/False values has no weight at all, but the short-circuit part has.
    – Hans
    Commented May 17, 2024 at 15:21

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.