×

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

What is Python 2

Python is a widely used high-level language. The initial work on developing python was begun in the late 1980s. In 1989, Guido Van Rossum started to work on it. Initially,...

3 minutes read.

Problem-solving with algorithm and data structures using Python

What is problem-solving? There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise...

3 minutes read.

Python List Methods

Python List Methods Python has a set of built-in methods that you can use on lists or arrays. Following are all of the methods of list objects: Methods Explanation append The list.append() method...

3 minutes read.

Python program to display ASCII value of the character

Python program to display ASCII value of the character The full form of ASCII is American Standard Code for Information Interchange. This example explains a program in Python to find the...

1 minute read.

How to comment out a block of code in Python

When you are writing code in Python, you may want to document it. You need to mention why a piece of code functions, for instance. Mathematics, algorithms, and intricate business...

4 minutes read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Managing Multiple Python Versions With pyenv

Introduction If you had ever wished to assist to an application that makes use of several different Python versions but weren't sure whether you would quickly test them all? Do you...

4 minutes read.

Python issubclass() Function

Python issubclass() Function The issubclass() function in Python returns a boolean value ‘True’ if the given object is a subclass of classinfo, else it returns False. Syntax issubclass(class, classinfo) Parameter class: It is a required parameter which represents a tuple...

1 minute read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the...

9 minutes read.

How to run Python code from the command prompt

The Windows operating system's command-line interpreter is CMD or Command Prompt. The "MS-DOS Prompt" is comparable to Command.com, used in DOS and Windows 9x computers. It is similar to Unix...

3 minutes read.

Python Hash Table

An Introduction to Hashing A technique which used to identify a particular object uniquely from a set of similar objects is known as Hashing. Some real-life examples of hashing implementations include: A...

9 minutes read.

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Paramiko Python Example

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...

6 minutes read.

Python And Operator

Python's and operator takes two operands that can be either object, Boolean expressions, or both. And operator creates more complex expressions using those operands. Conditions are the common name for...

8 minutes read.

Captcha Code in Python with Example

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...

6 minutes read.

Python Support

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.

Python property()

Python property() class The property() class in Python returns a property attribute. Syntax class property(fget=None, fset=None, fdel=None, doc=None) Parameter fget: This attribute is used for getting an attribute value. fset : This parameter sets an attribute value. fdel: It is a function for deleting...

1 minute read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.