In Python, we don’t have a built-in ‘contains’ method for checking if there is a substring in strings. However, there are a few ways to check if a string contains a substring. Checking if a substring exists within a string is a fundamental task that is used in data processing, searching, and text analysis. Python gives several methods that range from simple operators to advanced ones such as regular expressions and functional programming tools.
This blog explores different approaches along with examples to help you master substring in Python.
Table Of Contents:
Python Substring in String
Checking for substring is one of the most common tasks in Python, and the language gives various methods to accomplish it like find(), index() , count(), and many more. Among these, the most optimized approach is by using the in operator which acts as a comparison operator and is fast to use.
1. Check Python Substring in String using the If-Else
if-else statement can be used to check if a substring exists in a string. It allows you to conditionally execute various blocks of code based on whether the condition is true or false.
For example, if you need to check whether a username is valid or not:
username = "harry_potter123" if "@" in username: print("Invalid username: Cannot contain '@'.") else: print("Username is valid.")
Output:
The username is valid.
Checking Python Substring in String using in Operator
The in operator is one of the most simple ways to check if there are any substrings.
For example, if you need to check if an email contains the domain:
string = "Learning programming from Intellipaat is enjoyable." substring = "programming" if substring in string: print("Substring found!") else: print("Substring not found.")
Output:
Substring found!
Checking Python Substring in String using split() method
The split() method divides the string into a list, which then can be checked for the substring.
For example, if there is a requirement for a keyword in a sentence:
test_sentence = "Welcome to Intellipaat!!" keywords = sentence.split() if "Intellipaat" in keywords: print("The sentence mentions Intellipaat.")
Output:
The sentence mentions Intellipaat.
Check Python Substring in String using find() method
The find() method is used to return the index of the substring and -1 when it is not found. It returns the first occurrence of the substring. It is useful for locating the position of a substring.It can handle cases where multiple substrings are present.
You can take the example to check if a product ID is valid or not:
testproduct_id = "NEW12345" if testproduct_id.find("123") != -1: print("Valid product ID.") else: print("Invalid product ID.")
Output:
Valid product ID.
Check Python Substring in String using count() Method
The count() function counts the number of times a substring appears in a string.
For example when you want to count the mentions of a word in the document:
test_text = "Welcome to Intellipaat. Intellipaat is a great place to learn new technology!!!" word_count = text.count("Intellipaat") print(f"The word 'Intellipaat' appears {word_count} times.")
Output:
The word ‘Intellipaat’’ appears 2 times.
Check Python Substring in string using index() method
index() method is similar to find(), but it raises an error if the substring is not found.
For example:
test_string = "Intellipaat makes learning easy." substring = "learning" try: test_position = test_string.index(substring) print(f"Substring found at index {test_position}.") except ValueError: print("Substring not found.")
Output:
Substring found at index 18.
Check Python Substring in String using List Comprehension
List comprehension can filter out the substrings from the multiple strings. It works by listing the comprehension that iterates over the substrings and then filters out the ones that are found in the string. It is mostly used when you are dealing with a list of substrings. For example:
string = "Python supports multiple programming paradigms." substrings = ["Python", "Java", "C++"] found = [sub for sub in substrings if sub in string] print("Found substrings:", found)
Output:
Found substrings: [‘Python’]
Check Python Substring in String using Lambda Function
Lambda functions simplify your substring checks for the dynamic operations.It is mostly used for one-liner substring checks, especially in your functional programming scenarios.
For example:
test_string = "Python is dynamic and powerful." substring = "dynamic" check = lambda s, sub: sub in s print("Substring found!" if check(string, substring) else "Substring not found.")
Output:
Substring found!
Check Python Substring in String using the “__contains__” magic class.
The __containes__ method is an internal function that is used by the in operator. It is mostly useful for understanding how in works in the backend.
For example:
test_string = "Python is simple yet powerful." test_substring = "simple" if test_string.__contains__(test_substring): print("Substring found!") else: print("Substring not found.")
Output:
Substring found!
Check Python Substring in String using Slicing
Slicing can be used to check for the substring like checking parts of the string. It is mostly used to check for the substring whose positions are already known to you.
For example:
test_string = "Python programming is easy to learn." test_substring = "programming" if test_string[7:18] == test_substring: print("Substring found!") else: print("Substring not found.")
Output:
Substring found!
Check Python Substring in String using Regular Expression
When you want a powerful module for matching patterns in strings, Regular expression re is best to use. It is ideal for advanced searches that include patterns with wildcards, repetitions, etc.
Example as a code:
import re test_string = "Python is simple, Python is versatile." test_pattern = "Python" if re.search(test_pattern, test_string): print("Substring found!") else: print("Substring not found.")
Output:
Substring found!
Check Python Substring in String using operator.contains() method
The operator.contains() method is a functional programming method that is equal to the in operator. You can use it when you are working with functional programming or tools such as map and filter.
For example:
import operator test_string = "Learning with Intellipaat!!." test_substring = "Intellipaat" if operator.contains(test_string, test_substring): print("Substring found!") else: print("Substring not found.")
Output:
Substring found!
Conclusion:
Python gives you various methods to check for the substrings, ranging from simple to advanced ones. Understanding these methods lets you choose the best approach according to your needs, which makes string manipulation in Python both versatile and effective.