Python str contains multiple

How to check if multiple strings exist in another string in Python?

Imagine a scenario where we must satisfy 50 requirements in order to work. To determine whether conditions are true, we typically employ conditional statements (if, if−else, elif, nested if). However, with so many conditions, the code grows long and unreadable due to the excessive use of if statements.

Python’s any() function is the only option for such circumstances, thus programmers must use it.

The first approach is by writing a function to check for any multiple strings’ existence and then using the ‘any’ function for checking if any case is True, if any case is True then, True is returned, otherwise False is returned

Example 1

In the example given below, we are taking a string as input and we are checking if there are any matches with the strings of the match using the any() function −

match = ['a','b','c','d','e'] str = "Welcome to Tutorialspoint" print("The given string is") print(str) print("Checking if the string contains the given strings") print(match) if any(c in str for c in match): print("True") else: print("False")

Output

The output of the above example is as shown below −

The given string is Welcome to Tutorialspoint Checking if the string contains the given strings ['a', 'b', 'c', 'd', 'e'] 15. True

Example 2

In the example given below, we are taking program same as above but we are taking a different string and checking −

match = ['a','b','c','d','e'] str = "zxvnmfg" print("The given string is") print(str) print("Checking if the string contains the given strings") print(match) if any(c in str for c in match): print("True") else: print("False")

Output

The output of the above example is given below −

The given string is zxvnmfg Checking if the string contains the given strings ['a', 'b', 'c', 'd', 'e'] False

Using Reggular Expressions

Regular expressions are used in the second method. Import the re library and install it if it isn’t already installed to use it. We’ll use Regex and the re.findall() function to see if any of the strings are present in another string after loading the re library.

Читайте также:  Static member class cpp

Example 1

In the example given below, we are taking a string as input and multiple strings and are checking if any of the multiple strings match with the string using Regular Expressions −

import re match = ['a','b','c','d','e'] str = "Welcome to Tutorialspoint" print("The given string is") print(str) print("Checking if the string contains the given strings") print(match) if any(re.findall('|'.join(match), str)): print("True") else: print("False")

Output

The output of the above example is as shown below −

The given string is Welcome to Tutorialspoint Checking if the string contains the given strings ['a', 'b', 'c', 'd', 'e'] True

Example 2

In the example given below, we are taking program same as above but we are taking a different string and checking −

import re match = ['a','b','c','d','e'] str = "zxvnmfg" print("The given string is") print(str) print("Checking if the string contains the given strings") print(match) if any(re.findall('|'.join(match), str)): print("True") else: print("False")

Output

The output of the above example is given below −

The given string is zxvnmfg Checking if the string contains the given strings ['a', 'b', 'c', 'd', 'e'] False

Источник

Python str contains multiple

Last updated: Feb 20, 2023
Reading time · 5 min

banner

# Table of Contents

# Check if one of multiple strings exists in another string

Use the any() function to check if multiple strings exist in another string.

The any() function will return True if at least one of the multiple strings exists in the string.

Copied!
my_str = 'apple, egg, avocado' list_of_strings = ['apple', 'banana', 'kiwi'] if any(substring in my_str for substring in list_of_strings): # 👇️ this runs print('At least one of the multiple strings exists in the string') else: print('None of the multiple strings exist in the string')

check if one of multiple strings exists in another string

If you need to check if ALL of multiple strings exist in another string, click on the following subheading.

We used a generator expression to iterate over the collection of strings.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

In the example, we iterate over the collection of strings and check if each string is contained in the other string.

The any function takes an iterable as an argument and returns True if any element in the iterable is truthy.

The any() function will short-circuit returning True if at least one string is contained in the other string.

# Getting the substring that is contained in the string

You can use the assignment expression syntax if you need to get the value that is contained in the string.

Copied!
my_str = 'apple, egg, avocado' list_of_strings = ['apple', 'banana', 'kiwi'] if any((match := substring) in my_str for substring in list_of_strings): # 👇️ this runs print('At least one of the multiple strings exists in the string') print(match) # 👉️ 'apple' else: print('None of the multiple strings exist in the string')

Assignment expressions allow us to assign to variables within an expression using the NAME := expression syntax.

If the iterable we pass to the any() function is empty or none of the elements in the iterable are truthy, the any function returns False .

# Getting one or more substrings that are contained in the string

Use the filter() method if you need to get one or more substrings that are contained in the string.

Copied!
my_str = 'apple, egg, kiwi' list_of_strings = ['one', 'two', 'apple', 'egg'] matches = list(filter(lambda x: x in my_str, list_of_strings)) print(matches) # 👉️ ['apple', 'egg']

getting one or more substrings that are contained in the string

The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

The lambda function we passed to filter gets called with each substring from the list.

The new list only contains the substrings that are contained in the string.

# Check if One of multiple Strings exists in another String using a for loop

You can also use a for loop to check if one of multiple strings exists in another string.

Copied!
my_str = 'apple, egg, avocado' list_of_strings = ['apple', 'banana', 'kiwi'] one_exists = False for substring in list_of_strings: if substring in my_str: one_exists = True break print(one_exists) # 👉️ True if one_exists: # 👇️ this runs print('At least one of the substrings is contained in the string') else: print('None of the substrings are contained in the string')

check if one of multiple strings exists in another string using for loop

We initialized the one_exists variable to False and used a for loop to iterate over the list of strings.

On each iteration, we check if the current substring is contained in the string.

If the condition is met, we set the one_exists variable to True and exit the for loop.

# Checking in a case-insensitive manner

If you need to check if one of multiple strings exists in another string in a case-insensitive manner, convert both strings to lowercase.

Copied!
my_str = 'APPLE, EGG, AVOCADO' list_of_strings = ['apple', 'banana', 'kiwi'] if any(substring.lower() in my_str.lower() for substring in list_of_strings): # 👇️ this runs print('At least one of the multiple strings exists in the string') # print(match) # 👉️ 'apple' else: print('None of the multiple strings exist in the string')

We used the str.lower() method to convert each substring and the string to lowercase before checking if each substring is contained in the string.

The str.lower method returns a copy of the string with all the cased characters converted to lowercase.

# Check if ALL of multiple strings exist in another string

Use the all() function to check if multiple strings exist in another string.

The all() function will return True if all of the substrings exist in the string and False otherwise.

Copied!
my_str = 'apple, egg, kiwi' list_of_strings = ['apple', 'egg', 'kiwi'] # ✅ check if ALL of multiple strings exist in another string if all(substring in my_str for substring in list_of_strings): # 👇️ this runs print('All of the substrings exist in the string') else: print('Not all of the substrings exist in the string')

We used a generator expression to iterate over the collection of strings.

The all() built-in function takes an iterable as an argument and returns True if all elements in the iterable are truthy (or the iterable is empty).

If any of the strings in the collection is not contained in the other string, the all() function will short-circuit returning False .

# Check if ALL of multiple strings exist in another string using a for loop

You can also use a for loop to check if all of multiple substrings exist in a string.

Copied!
my_str = 'apple, egg, kiwi' list_of_strings = ['apple', 'egg', 'kiwi'] all_exist = True for substring in list_of_strings: if not substring in my_str: all_exist = False break print(all_exist) # 👉️ True if all_exist: # 👇️ this runs print('All of the substrings exist in the string') else: print('Not all of the substrings exist in the string')

We initialized the all_exist variable to True and used a for loop to iterate over the list of strings.

On each iteration, we check if the current substring is not contained in the string.

If the condition is met, we set the all_exist variable to False and exit the for loop.

The break statement breaks out of the innermost enclosing for or while loop.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to check if multiple strings exist in another string in Python?

Imagine a scenario where we must satisfy 50 requirements in order to work. To determine whether conditions are true, we typically employ conditional statements (if, if−else, elif, nested if). However, with so many conditions, the code grows long and unreadable due to the excessive use of if statements.

Python’s any() function is the only option for such circumstances, thus programmers must use it.

The first approach is by writing a function to check for any multiple strings’ existence and then using the ‘any’ function for checking if any case is True, if any case is True then, True is returned, otherwise False is returned

Example 1

In the example given below, we are taking a string as input and we are checking if there are any matches with the strings of the match using the any() function −

match = ['a','b','c','d','e'] str = "Welcome to Tutorialspoint" print("The given string is") print(str) print("Checking if the string contains the given strings") print(match) if any(c in str for c in match): print("True") else: print("False")

Output

The output of the above example is as shown below −

The given string is Welcome to Tutorialspoint Checking if the string contains the given strings ['a', 'b', 'c', 'd', 'e'] 15. True

Example 2

In the example given below, we are taking program same as above but we are taking a different string and checking −

match = ['a','b','c','d','e'] str = "zxvnmfg" print("The given string is") print(str) print("Checking if the string contains the given strings") print(match) if any(c in str for c in match): print("True") else: print("False")

Output

The output of the above example is given below −

The given string is zxvnmfg Checking if the string contains the given strings ['a', 'b', 'c', 'd', 'e'] False

Using Reggular Expressions

Regular expressions are used in the second method. Import the re library and install it if it isn’t already installed to use it. We’ll use Regex and the re.findall() function to see if any of the strings are present in another string after loading the re library.

Example 1

In the example given below, we are taking a string as input and multiple strings and are checking if any of the multiple strings match with the string using Regular Expressions −

import re match = ['a','b','c','d','e'] str = "Welcome to Tutorialspoint" print("The given string is") print(str) print("Checking if the string contains the given strings") print(match) if any(re.findall('|'.join(match), str)): print("True") else: print("False")

Output

The output of the above example is as shown below −

The given string is Welcome to Tutorialspoint Checking if the string contains the given strings ['a', 'b', 'c', 'd', 'e'] True

Example 2

In the example given below, we are taking program same as above but we are taking a different string and checking −

import re match = ['a','b','c','d','e'] str = "zxvnmfg" print("The given string is") print(str) print("Checking if the string contains the given strings") print(match) if any(re.findall('|'.join(match), str)): print("True") else: print("False")

Output

The output of the above example is given below −

The given string is zxvnmfg Checking if the string contains the given strings ['a', 'b', 'c', 'd', 'e'] False

Источник

Оцените статью