- Python String Contains – See if String Contains a Substring
- Option 1: if . in
- Option 2: find()
- Option 3: Regex search()
- Summary
- Python: Check if String Contains Substring
- The in Operator
- The String.index() Method
- The String.find() Method
- Free eBook: Git Essentials
- Regular Expressions (RegEx)
- About the Author
- How to Check if a Python String Contains a Substring?
- Methods to check if a Python string contains a substring
- Using the find() Method
- Using the ‘in’ operator
- Using the count() Method
- Using the index() Method
- Using the operator.contains() Method
- Conclusion
Python String Contains – See if String Contains a Substring
An easy way to check if a string contains a particular phrase is by using an if . in statement. We can do this as follows:
Today we’ll take a look at the various options you’ve got for checking if a string contains a substring. We’ll start by exploring the use of if . in statements, followed by using the find() function. Towards the end, there is also a section on employing regular expressions (regex) with re.search() to search strings.
Option 1: if . in
The example above demonstrated a quick way to find a substring within another string using an if . in statement. The statement will return True if the string does contain what we’re looking for and False if not. See below for an extension of the example used previously:
The output displays that our if . in statement looking for ‘apples’ only returned True for the first item in strings , which is correct.
It’s worth mentioning that if . in statements are case-sensitive. The line if ‘apples’ in string: wouldn’t detect ‘Apples’ . One way of correcting this is by using the lower() method, which converts all string characters into lowercase.
We can utilize the lower() method with the change below:
Alternatively, we could use the upper() function to search for ‘APPLES’ instead.
The if .. in approach has the fastest performance in most cases. It also has excellent readability, making it easy for other developers to understand what a script does.
Of the three options listed in this article, using if . in is usually the best approach for seeing if a string contains a substring. Remember that the simplest solution is quite often the best one!
Option 2: find()
Another option you’ve got for searching a string is using the find() method. If the argument we provide find() exists in a string, then the function will return the start location index of the substring we’re looking for. If not, then the function will return -1. The image below shows how string characters are assigned indexes:
We can apply find() to the first if . in example as follows:
For the first list item, ‘apples’ started at index 16, so find(‘apples’) returns 16. ‘apples’ isn’t in the string for the other two items, so find(‘apples’) returns -1.
The index() function can be used similarly and will also return the starting index of its argument. The disadvantage of using index() is that it will throw ValueError: substring not found if Python can’t find the argument. The find() and index() functions are also both case-sensitive.
Option 3: Regex search()
Regex is short for regular expression, which is kind of like its own programming language. Through re.search , a regex search, we can determine if a string matches a pattern. The re.search() function generates a Match object if the pattern makes a match.
Looking at the Match object, span gives us the start and end index for ‘apples’ . Slicing the string using ‘This string has apples'[16:22] returns the substring ‘apples’ . The match field shows us the part of the string that was a match, which can be helpful when searching for a range of possible substrings that meet the search conditions.
We can access the span and match attributes using the span() and group() methods, as follows:
If the substring isn’t a match, we get the null value None instead of getting a Match object. See the example below for how we can apply regex to the string problem we’ve been using:
In this case, the if statement determines if re.search() returns anything other than None .
We could argue that regex might be overkill for a simple functionality like this. But something like the example above is a great starting point for regex, which has plenty of other capabilities.
For instance, we could change the first argument of the search() function to ‘apples|oranges’ , where | is the «OR» logical operator. In this context re.search() would return a match object for any strings with the substring ‘apples’ or ‘oranges’ .
The following demonstrates an example of this:
Summary
The easiest and most effective way to see if a string contains a substring is by using if . in statements, which return True if the substring is detected. Alternatively, by using the find() function, it’s possible to get the index that a substring starts at, or -1 if Python can’t find the substring. REGEX is also an option, with re.search() generating a Match object if Python finds the first argument within the second one.
Python: Check if String Contains Substring
Checking whether a string contains a substring aids to generalize conditionals and create more flexible code. Additionally, depending on your domain model — checking if a string contains a substring may also allow you to infer fields of an object, if a string encodes a field in itself.
In this guide, we’ll take a look at how to check if a string contains a substring in Python.
The in Operator
The easiest way to check if a Python string contains a substring is to use the in operator.
The in operator is used to check data structures for membership in Python. It returns a Boolean (either True or False ). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring:
fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!") else: print("Not found!")
This operator is shorthand for calling an object’s __contains__ method, and also works well for checking if an item exists in a list. It’s worth noting that it’s not null-safe, so if our fullstring was pointing to None , an exception would be thrown:
TypeError: argument of type 'NoneType' is not iterable
To avoid this, you’ll first want to check whether it points to None or not:
fullstring = None substring = "tack" if fullstring != None and substring in fullstring: print("Found!") else: print("Not found!")
The String.index() Method
The String type in Python has a method called index() that can be used to find the starting index of the first occurrence of a substring in a string.
If the substring is not found, a ValueError exception is thrown, which can be handled with a try-except-else block:
fullstring = "StackAbuse" substring = "tack" try: fullstring.index(substring) except ValueError: print("Not found!") else: print("Found!")
This method is useful if you also need to know the position of the substring, as opposed to just its existence within the full string. The method itself returns the index:
print(fullstring.index(substring)) # 1
Though — for the sake of checking whether a string contains a substring, this is a verbose approach.
The String.find() Method
The String class has another method called find() which is more convenient to use than index() , mainly because we don’t need to worry about handling any exceptions.
If find() doesn’t find a match, it returns -1, otherwise it returns the left-most index of the substring in the larger string:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
fullstring = "StackAbuse" substring = "tack" if fullstring.find(substring) != -1: print("Found!") else: print("Not found!")
Naturally, it performs the same search as index() and returns the index of the start of the substring within the parent string:
print(fullstring.find(substring)) # 1
Regular Expressions (RegEx)
Regular expressions provide a more flexible (albeit more complex) way to check strings for pattern matching. With Regular Expressions, you can perform flexible and powerful searches through much larger search spaces, rather than simple checks, like previous ones.
Python is shipped with a built-in module for regular expressions, called re . The re module contains a function called search() , which we can use to match a substring pattern:
from re import search fullstring = "StackAbuse" substring = "tack" if search(substring, fullstring): print "Found!" else: print "Not found!"
This method is best if you are needing a more complex matching function, like case insensitive matching, or if you’re dealing with large search spaces. Otherwise the complication and slower speed of regex should be avoided for simple substring matching use-cases.
About the Author
This article was written by Jacob Stopak, a software consultant and developer with passion for helping others improve their lives through code. Jacob is the creator of Initial Commit — a site dedicated to helping curious developers learn how their favorite programs are coded. Its featured project helps people learn Git at the code level.
How to Check if a Python String Contains a Substring?
A substring is a sequence of characters within a String. When writing a Python program you may need to check whether a substring is present inside another string or not, there can be many reasons for that like searching and filtering data, input validation, etc.
To check if a string contains a substring, we can utilise many built-in functions that Python provides us, each one with slightly different functionality.
At the end of this tutorial, you will not only know how to check for substrings but also know a lot of new Python methods, so let’s get started.
Methods to check if a Python string contains a substring
Python has various methods for this check, but we’ll be using those that are easy to implement and require only a few lines of code.
The following are the methods in Python to check if a string contains other substrings.
- Using find() method
- Using in operator
- Using count() method
- Using index() method
- Using operator.contains() method
Now, let’s examine each of them separately, along with their respective syntax and examples.
Using the find() Method
The find() method is used to check whether a string contains a particular substring or not. It takes a substring as an argument and if the string contains that particular substring, it returns the starting index of the substring else it returns -1.
Here, substring is the string you want to search, and string is the string object in which you want to search.
str="Safa Mulani is a student of Engineering discipline." sub1="Safa" sub2="Engineering" print(str.find(substring1)) print(str.find(substring2))
Using the ‘in’ operator
The ‘in’ operator checks for the presence of a substring within a string by returning either True or False. If the substring is present it returns True else it returns False.
str="Safa Mulani is a student of Engineering discipline." sub1="Safa" sub2="Done" print(sub1 in str) print(sub2 in str)
Using the count() Method
The count() method checks for the occurrence of a substring in a string. If the substring is not found in the string, it returns 0.
str="Safa Mulani is a student of Engineering discipline." sub1="Safa" sub2="student" sub3="Done" print(str.count(sub1)) print(str.count(sub2)) print(str.count(sub3))
Using the index() Method
This method can also check for a substring’s presence in a string. If the substring is not present in the string then it doesn’t return any value, rather it generates a ValueError.
str = "Safa is a Student." try : result = str.index("Safa") print ("Safa is present in the string.") except : print ("Safa is not present in the string.")
Safa is present in the string.
Using the operator.contains() Method
We can also use the operator.contains() method of the “operator” module to check for substrings. It takes a string and a substring as an argument and returns a boolean True if the substring is contained in that string, else it returns False.
operator.contains(string, substring)
import operator str = "Safa is a Student." if operator.contains(str, "Student"): print ("Student is present in the string.") else : print ("Student is not present in the string.")
Student is present in the string.
Conclusion
In this tutorial, we explored five ways to check if a string contains a substring. Each method offers its own advantages and suitability for different scenarios. Among them, the best way to check whether a Python string contains another string is to use for loop , as it is easily understandable by beginners, more readable and does not require any additional methods.
With this knowledge, you can efficiently check if string contains a substring in Python programming language. Additionally, there is another method, string.__contains__(), which provides a more efficient way of performing this check. For a detailed tutorial specifically covering this method, you can read “Python String Contains: Check if a String Contains a Substring“. Hope you have enjoyed reading the content.