Checking Substrings in Python

In Python, Strings are frequently used in data processing and analysis. One common requirement is to check whether a particular substring exists within a string. This operation is essential for data validation, parsing, and filtering tasks. In this tutorial, we will explore various methods to determine if a string contains another string (substring) in Python.

Prerequisites: Before we explore methods, make sure you have a basic understanding of Python and Strings. No additional libraries are needed for these examples, As we will use native Python functionality.

Using the ‘in’ Operator for Checking Substrings in Python

The 'in' operator is the most straightforward way to check if a string contains another string. It returns ‘True’ if the substring exists within the string otherwise it returns ‘False’.

Output

Using the 'in' Operator for Checking Substrings in Python

In the above example, the Python program checks if the word “welcome” is present in the given text and prints the result accordingly.

Using the ‘find()’ Method for Checking Substrings in Python

The 'find()'method searches for specified values and returns the position where it was found. If the value is not found, the method returns -1.

Output

Using the 'find()' Method for Checking Substrings in Python

This method is particularly useful when you also want to know the position of the substring within the string.

Using the ‘index()’ Method for Checking Substrings in Python

Similar to 'find()' the 'index()' method returns the position of the substring within the string. However, if the substring is not found it raises a ValueError instead of returning -1.

Output

Using the 'index()' Method for Checking Substrings in Python

This method is beneficial when you need to ensure that the substring exists otherwise you want an exception to be raised.

Using Regular Expressions for Checking Substrings in Python

Regular expression(regex) provides a powerful way to search patterns within the text. The re module in Python is used for working with regular expressions.

Output

Using Regular Expressions for Checking Substrings in Python

Regular expressions are particularly useful when the substring pattern is complex or involves special characters.

Checking whether a string contains another string is a common task in Python programming. In this tutorial, we explore several methods to accomplish this. Each method has its use cases and advantages, so you can choose the one that best fits your needs.

Happy Coding & Learning

See Also

Leave a Comment