In this tutorial let’s learn about How to Check if a String Contains Substring in Python. We frequently need to check whether a given string contains a specified substring. We will list different ways here and then compare their running time performance to determine which method is the most efficient.
Contents
in
Operator to Check if a String Contains a Substring | Python
The in operator is the simplest way to see if a Python string contains a substring.
In Python, the in operator is used to examine data structures for membership. It yields a Boolean value (either True or False). For example, a in b is tested as True if a is a member of b, or b contains a. If the string b includes the substring a, it returns True.
Code Example :
string = "SimilarGeeks"
substring = "Similar"
if substring in string:
print("True")
else:
print("False")
Output :
True
Check whether a String Contains a Substring using String Methods in Python
Python includes a few string methods for determining whether a string contains a substring. We’ll look at the find() and index() methods among the other ways.
These methods locate and return the substring’s index. They do, however, have a few drawbacks, which we shall go over in detail.
String.index()
Method to Check whether a String Contains a Substring | Python
The index() function returns the position of the first appearance of a substring in the given string. It is the same as the find() method, except that it throws an exception if a substring is not found. When the substring sub is not found, it will throw a ValueError.
Syntax for String.index()
string.index(substring, start, end)
Code Example :
string = "SimilarGeeks"
substring = "Geeks"
try:
pos = string.index(substring)
except ValueError:
print("Not found!")
else:
print('The substring starts at index :',pos)
Output :
The substring starts at index : 7
String.find()
Method to Check if a String Contains a Substring | Python
The string.find() method is a string method that may be used to validate our query. Python String find() is a method in the Python library that returns the index of the first occurrence of a substring in the specified string. If the desired substring is not present in the given string, the string find() function will return -1 instead of throwing an exception.
Syntax for string.find()
string.find(substring, start, end)
Code Example :
string = "SimilarGeeks"
substring = "Geeks"
pos = string.find(substring)
if pos != -1:
print('The substring starts at index :',pos)
else:
print('Not Found')
Output :
The substring starts at index : 7
Check if a String Contains a Substring using Regular Expressions | Python
Regular expressions allow you to check strings for pattern matching in a more flexible way. Python includes a built-in module for regular expressions known as re. The search() function in the re module can be used to match a substring pattern:
Code Example :
import re
string = "SimilarGeeks"
substring = "Geeks"
# re.search()
if re.search( substring, string ):
print("String '{0}' is present in string '{1}' " .format(substring,string))
else:
print("String '{0}' is not present in string {1} " .format(substring,string))
Output :
String ‘Geeks’ is present in string ‘SimilarGeeks’
This way is preferable if you require a more advanced matching function, such as case insensitive matching. Otherwise, for basic substring matching use-cases, the complexities and slower speed of regex should be avoided.
Conclusion
In this tutorial we learnt different ways to Check if a String Contains Substring in Python. We went through in
operator, string methods like index()
and find()
, then regular expressions. The in
operator should be used to verify whether a substring exists in the given string because it is the fastest. str.find() and str.index() could also be used but are not optimal due to low performance.
Similar Posts:
Convert String to Datetime in Python
How to Extract numbers from a String in Python