×

Checking whether a String Contains a Set of Characters in python

In this tutorial, we will learn how to examine or check whether a string contains any set of characters or a substring and if it contains, we will learn how to know the occurrence of a particular character. Python, a user-friendly language, provides several built-in functions to check the presence of a set of characters in a string. Now, Let us learn various techniques to determine the substring present in a string. Here, we will see different methods to achieve our target, and further, we will see how to implement this through an example.

Following are the methods available in Python to examine the presence of a string containing a set of characters or a substring.

1. By means of the "in" operator available in Python

The easiest and quickest method to examine if a substring is present or not in a string is through the application of the "in" operator. This operator yields true if the character is present in a string. Otherwise, it yields false.

Python in method takes two arguments. One resides on the left-hand side, and the other resides on the right-hand side. It is sensitive to cases, so it treats lower and upper case characters differently.

Example 1:

#Python program to check if a substring is present in a larger string or not


str="bonjour, Bonne nuit, bonsoir World, chat, monsieur, chieval"
print ("World" in str)

Output:

Checking Whether A String Contains A Set Of Characters

Explanation:

In the above example, we have checked the presence of ‘World’ in the string through in keyword. It yields output as true as 'world' in the provided string.

Example 2:

#Python program to check whether a substring is present in a string or not


str="bonjour, Bonne nuit, bonsoir World, chat, chieval"
print ("hello" in str)

Output:

Checking Whether A String Contains A Set Of Characters

Explanation:

In the above example, we have checked the presence of ‘World’ in the string through in keyword. It yields output as false as ‘world’ is not present in the provided string.

Example 3:

This is another example of understanding the working of in method in python language.

# Python 3 code to understand how to
# Check substring present in a string
# through the means of in operator


# Initialization of the string
test_str1 = "this_is_for_you"


# using in method to check the presence of substring


print ("Does for exists in this_is_for_you ? : ")
if "for" in test_str1 :
	print ("Yes, String is found")
else :
	print ("No, String is not found")

Output:

Checking Whether A String Contains A Set Of Characters

Explanation:

In the above example, We have tried to check the presence of substring ‘for’ in the string test_str1  ‘this_is_for_you’ using the ‘in’ method. Since the word for was present in the provided string, we received the output saying yes, a string is found.

2. By means of str. find() method.

The above method is usually taken into account to obtain used the lowermost index at which the string occurs but also returns -1. If the string is not present, it yields -1 as output. Thus, the string is present if the returned value is greater than 0. Otherwise, it is not present.

Example:

# Python 3 code to understand how to
# check the presence of a substring in a  string
# using str.find() method


# initialization of string
test_str1 = " this_is_for_you "


# using str.find() to test the presence of 
# for substring
res1 = test_str1.find("for")
if res1 >= 0:
	print (" for is present in this_is_for_you ")
else :
	print (" for is not present in this_is_for_you ")

Output:

Checking Whether A String Contains A Set Of Characters

Explanation:

In the above example, We have tried to check the presence of substring ‘for’ in string ‘this_is_for_you’ using the str. find() method. Since the word for was present, we received the output saying ‘for is present in the string’.

3. By means of the str. index()

To perform the analogous task, this method can be used. It differs from the str. find() method as it doesn't return any value like the former. Instead of returning a value, it returns a ValueError if the string is not present. Thus catching the exception is the technique of checking for the presence of a substring in a string. 

Example:

# Python 3 code to demonstrate
# checking substring in string
# using str.index()


# initializing string
test_str = "this_is_for_you"


# using str.index() method to test the presence of
# moon substring
try :
	res = test_str.index("moon")
	print ("moon exists in ")
except :
	print ("moon does not exists in this_is_for_you")

Output:

Checking Whether A String Contains A Set Of Characters

Explanation:

In the above example, we have tried to check the presence of substring ‘moon’ in string ‘this_is_for_you’ using the str. index () method. Since the word moon was not present in the provided string, we received the output saying ‘moon does not exist in this_is_for_you’.

4. By means of the operator.contains() method

This is a less popular method to examine whether a substring is present in a string or not. This method is also operative in completing the job of inspecting a string in a string.

# Python 3 code to understand how to
# check the presence of a substring in string
# using operator.contains() method


import operator


# initialization of a string
test_str1 = " this_is_for_you "


# using operator. contains() to test the presence of
# for substring


if operator.contains(test_str1, "for"):
	print ("for is present in this_is_for_you ")


else :
	print ("for is not present in this_is_for_you  ")

Output:

Checking Whether A String Contains A Set Of Characters

Explanation:

In the above example, using an operator, we have tried to check the presence of substring 'for' in string 'this_is_for_you'.contains() method. Since the word for was present in the string, we received the output in the above manner.

5. By means of String.count() function:

This function is considered to keep track or count the occurrence of an element in the string. It can be very useful in checking the occurrence of a particular element in a large string. If the searched string exists in the larger string, the function returns some number, and if it doesn't exist, 0 is returned by the function.

Example:

# Python 3 code to understand how to
# check the presence of a substring in a string
# using String.count() method


# initialization of string
test_str1 = " this_is_for_you "


            # Substring whose presence is to be checked




temp1 = "for"


# using string.count to test the presence of  ‘for’ substring
ans1 = test_str1.count(temp1)
# Printing our result


if ans1:
	print ("for is present in this_is_for_you ")
else :
	print ("for is not present in this_is_for_you ")

Output:

Checking Whether A String Contains A Set Of Characters

Explanation:

In the above example, we have tried to check the presence of substring ‘for’ in the string ‘this_is_for_you’ using string. Count method. Since the word was present, we received the output in the above manner.

6. By means of re.search() function:

The regular expressions in Python are popularly used to match the patterns.

This function is taken into account to find out the pattern lying in the string.

A sub-string can be taken into account as a pattern to search in string.

Example:

# code is written in  Python version 3 to understand how to
# check the presence of a substring in the string
# by means of  re.search() function


import re
# initialization of the string
test_str1 = "this is for you"


# Substring whose presence is to be checked
temp1 = "is"


# by means of re.search method to test for substring
ans1 = re.search(temp1, test_str1)


# Printing the output 
if ans1:
	print ("is present in this is for you")
else :
	print ("is is not present in this is for you")

Output:

Checking Whether A String Contains A Set Of Characters

Explanation:

In the above example, we have tried to check the presence of substring ‘is’ in the string ‘this_is_for_you’ using Python's regular method called re. search. Since the word is was present in the string, we received the above output.

Summary:

In this module, we studied how to check the presence of a substring or a character in a larger string in a python programming language. We saw various techniques to check this. We can do this by applying the following five methods: in method, regular expressions. search() method, str. find() method, operator.contains() method, string.count() function. We saw examples for each of the above methods to understand the implications in a better way.


Related Topics

Python Write Excel File

Python Write Excel File The Python xlwt module is used to write an excel file and perform multiple operations on it. It can be used to write text, numbers, and formulas for multiple...

3 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

How to Iterate a List in Python

As we know, a List is one of the four unique data structures available in Python; in this article, we will deep dive into understanding iterating through a list and...

3 minutes read.

Length of Tuple in Python

What is Tuple? Python is a data structure in a python programming language; it is the collection of the objects in a sequence. The tuples are immutable; that is, we cannot...

3 minutes read.

Python program to sort the array element into ascending order

Python program to sort the array element into ascending order In this example, we'll see how to sort the array elements in ascending order using a Python program. Sorting is a...

2 minutes read.

Python Sys Stdout

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

After Python, What Should I Learn

Python is a programming language used to create websites, software, and other projects. It is easy to code and easy to learn. After learning Python, there are many different directions...

4 minutes read.

Artificial intelligence mini projects ideas in python

Artificial intelligence "The human race started from the invention of the wheel", and today we are about to advance to the Industrial level 4.0, where machines can work, talk, think and...

6 minutes read.

Python Os sep

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to Install Python In Windows

How To Install Python In Windows? Python is a language that every aspirant developer looks forward to. One thing we must keep in our mind is how to begin our hands-on...

3 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

Python Project Ideas

One of the most widely used programming languages today is Python. This pattern appears set to continue through 2023 and beyond. Therefore, working on some current Python project ideas is the...

10 minutes read.

Scraping data in python

Data scraping is a technique in which one program extracts a set of data from the output of another program. Web scraping is the most common application of this technique....

6 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Recursive Multiplication Python

Recursive Multiplication Python In this tutorial, we will learn how to write a Python program to get the multiplication of two numbers using the recursive approach. In the recursive multiplication approach, we...

2 minutes read.

How to build an Auto Clicker using Python?

What is an Auto Clicker? An Auto Clicker is software that is used for automating the click of a mouse on any particular element on the computer screen and controlling the...

8 minutes read.