Check if multiple strings exist in a string in Python

In this Python tutorial, we will learn about different methods through which we can check if multiple strings exist in another string in python.

Table Of Contents

Method 1 : Using for loop

First method that we will be using to check if multiple strings exist in another string in python is by using the in operator in for loop.

Suppose we have a list of strings and a big string. We want to check if all strings from the list exist in the big string or not. For that we will iterate over all the substrings in the list and check if all of them exists in big string using the in operator.

See the example code below :

Advertisements

CODE:

listOfStr = ['big', 'this', 'is']

bigStr = "this is a big string"

result = True
for substr in listOfStr:
    if substr not in bigStr:
        result = False
        break

if result:
    print('All strings from the list exist in the big string')
else:
    print('No, not all strings from the list exist in the big string')

OUTPUT:

All strings from the list exist in the big string

Here we are checked if all the strings in list exist in a big string or not. If you want to check if any string from the list exist in big string, then implementation is little different,

listOfStr = ['why', 'this', 'any', 'here', 'how']

bigStr = "this is a big string"

result = False
for substr in listOfStr:
    if substr in bigStr:
        result = True
        break

if result:
    print('A string from the list exist in the big string')
else:
    print('No string from the list exist in the big string')

Output

A string from the list exist in the big string

Here, we iterate over all the strings in the list and for each string we checked if it exists in the big string or not. If any string from list exists in the big string, then break the loop and print the result.

Method 2 : Using any() function :

Second method that we will be using is the any(iterable) function. It returns True if the given iterable has any True value, otherwise it returns False, which here means not found. Here we will use some alphabets which will be stored in a list then we will compare it with a string to check if multiple strings exists in another string.
See the example code below :

CODE :

# list of alphabets which need to be checked
alphabets = ['z','a','p']

str_var = 'Python Programming Language Tutorial'

# looping through alphabets then checking with any() method
if any(c in str_var for c in alphabets ):
    print ("Found ")

OUTPUT :

Found 

In above code and output you can see by using any() function we have checked whether a string or any string from the multiple strings are present in another big string or not. Here you can see some characters of alphabets list are present in str_var.

Method 3 : Using re.findall()

Antoher method that we can use to check if multiple strings exist in another string in Python is the findall() method of Regex module. The re stands for Regular Expression which comes bundled with Python, mainly used for matching expressions. Here we will also be using any() method. See the example below :

CODE :

import re

alphabets = ['s','b','c','p','l']

str_var = 'Python Programming Language Tutorial'

# Check if any string from the list exist in the big string
if any(re.findall('|'.join(alphabets), str_var)): 
    print ('Found ')

OUTPUT :

Found 

In above example code and output you can see we used a combination of finadll() and any() to check if multiple strings exist in another string in Python. We first joined all the strings in the list to create a regex pattern i.e. “s|b|c|p|l” and then passed that pattern to the findall(). It will return a sequence of matched objects. If not a single match is found the it will return an empty sequence. We used the any() function to check if any element is present in the returned sequence or not.

Method 4 : Using For Loop and if

Next method that we will be using is the best solution to this problem. In this method, we will store the matching alphabets in the found var and then we will check if it has something inside it or not. The found variable will have matching elements store inside it. See the example below :

CODE :

alphabets = ['P','b','r','c','z','p']
str_var = 'Python Programming Language Tutorial'

# will store the matching alphabets 
found = [x for x in str_var if x in alphabets]

# checks if found vas has something in it or not
if found:
    print('Found these alphabets :',found) 
else:
    print('Not found')

OUTPUT :

Found these alphabets : ['P', 'P', 'r', 'r', 'r']

As you can see in above code and output, we have some mathcing elements and by using this method we have successfully found all the strings matching in alphabets vas and str_var. Also you may notice this program is case sensitive. Like we have both capital P and small p in the alphabets but in str_var we have only captial P , thats why in found varibale we can only find capital P.

Summary

So in this article, we learned about four different methods through which we can check if multiple strings exist in another string in Pyhton. Basically you can use all the above methods according to your need but the most useful method may be the method 4 because in it you can get all the mathcing chars also it is easy to understand and does not uses many functions , it only uses for and if.

Always read the example codes and try on your local machines. Python 3.10.1 for writing examples. Type python –version to check your python version. Happy Coding.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top