Checking if a String Contains a Substring in Python

To check if a Python string contains the desired substring, you can use the "in" operator or the string.find() method. To get the first index of a substring in a string, you can use the string.index(). To count the number of substrings in a string, you can use the string.count(). Regular expressions provide the most advanced way to find and manipulate strings in Python. In this Python String Contains example, we check if the string contains a substring using the "in" operator. Other methods for finding a substring in a string are listed below with detailed explanations. Click Execute to run the Python String Contains example online and result.
Checking if a String Contains a Substring in Python Execute
if 'str' in 'striing':
    print("Found!")
Updated: Viewed: 9259 times

What are strings in Python?

A Python string is a set of characters, words, or punctuation marks enclosed in single, double, or triple quotes. Internally, Python stores strings as an array of 16-bit Unicode bytes (and 8-bit ASCII bytes for Python 2), and each character in the string is denoted by one byte. Python strings are immutable. Once created, they cannot be changed. String manipulation methods always create a new string instead of modifying the existing one. Python has no dedicated data type for a single character; it is simply a string of length 1.

Single characters in a string can be accessed by index using the "[]" operator. You can use single quotes in strings enclosed in double quotes, and vice versa. Strings created using single and double quotes are identical. But you cannot mix them, as this will lead to a syntax error.

Python's built-in "str" module provides an extensive list of methods for searching, concatenating, reversing, splitting, comparing strings, and more.

Basic method for checking a substring in a string

The easiest and fastest way to check if a string contains a substring is to use the Python "in" and "not in" operators. The "in" operator will return True or False depending on whether the string contains the specified substring or not:

Checking for a substring in a string using the 'in' operator
fruits = 'apple, pear, banana'

print('apple' in fruits)
# True

print('apple' not in fruits)
# False

Checking if a string contains a substring using the string.find() method

The "in" operator is helpful when you need to check if a string contains a substring, but it is not suitable when you want to find the position of a substring in a string. If you need to get the index of a substring, you can use the string.find() method. The string.find() method returns the index of the substring in the string starting at zero or -1 if it finds nothing.

Get the position of a substring in a string
fruits = 'apple, pear, banana'

print(fruits.find('pear'))
# 7

print(fruits.find('peach'))
# -1

If a substring is repeated multiple times in a string, the index of the first occurrence will be returned.

Get the position of the first occurrence of a substring in a string
apples = 'apple-1, apple-2, apple-3'

print(apples.find('apple'))

# 0

The string.find() method is case sensitive; you may need to lowercase the string and substring so that the string.find() method can search correctly, or you can use Regular Expressions.

The string.find() method is case sensitive
fruits = 'Apple, Pear, Banana'

print(fruits.find('apple'))
# -1

print(fruits.find('Apple'))
# 0

print(fruits.lower().find('Apple'.lower()))
# 0

How to find a substring in a string, starting at some position?

By default, the string.find() method searches the entire string. If you only want to search for a specific part of the string, you can pass the start and end positions to the string.find() method.

Search for a substring in a specific part of a string
apples = 'apple-1, apple-2, apple-3'

print(apples.find('apple'))
# 0

print(apples.find('apple', 7))
# 9

print(apples.find('apple', 16))
# 18

How can I check if a string contains a substring in reverse order (right to left)?

If you need to search from the end of the string, you can use the string.rfind() method. It works the same as string.find(), but starts searching from the end.

Search for a substring from the end of the string
apples = 'apple-1, apple-2, apple-3'

print(apples.find('apple'))
# 0

print(apples.rfind('apple'))
# 18

How to check if a string contains a substring using the string.index() method?

To find a substring in a string, you can also use the string.index() method. The string.index() method is similar to the string.find() and returns the index of the first occurrence of a substring in string. The string.index() method, unlike the string.find() method will raise a ValueError if the string does not contain a substring.

Searching a string using the index() method
fruits = 'apple, pear, banana'

print(fruits.index('apple'))
# 0

print(fruits.index('peach'))
# Traceback (most recent call last):
#   File "your_file_path", line 6, in 
#     print(fruits.index('peach'))
# ValueError: substring not found

To handle the ValueError exception, you can use the try/except block

Handling ValueError exception when using the index() method
fruits = 'apple, pear, banana'

try:
  fruits.index('peach')
except ValueError:
  print("There is no peach in the fruits")
else:
  print(fruits.index('peach'))
# There is no peach in the fruits

How to count a number of substrings in a string?

To count the number of substrings in a string, you can use the string.count() method.

Count the number of substrings in a string
apples = 'apple-1, apple-2, apple-3'

print(apples.count('apple'))

# 3

How to test if a string contains a substring using Regular Expressions?

The most advanced method for working with text in Python is using regular expressions. Regular expressions allow you to quickly check if a string contains a substring without converting them to lowercase. Unlike the "in", "find", and "index" methods, when searching with regular expressions, you can use patterns and perform more complex searches. However, regular expressions are slower than the "in" an operator and the string.find() and string.index() methods.

Check if string contains substring using regular expressions
from re import search, IGNORECASE

fruits = 'Apple, Pear, Banana'

print(search('Pear', fruits))
# <re.Match object; span=(7, 11), match='Pear'>

print(search('pear', fruits))
# None

print(search('pear', fruits, IGNORECASE))
# <re.Match object; span=(7, 11), match='Pear'>

How to count the number of substrings in a string using Regular Expressions?

To find out the number of occurrences of a substring in a string using regular expressions, you can use the re.findall() method and call the len() method on the result.

Count the number of substrings in a string using regular expressions
from re import findall

fruits = apples = 'apple-1, apple-2, apple-3'

print(findall('apple', apples))
# ['apple', 'apple', 'apple']

print(len(findall('apple', fruits)))
# 3

Alternative ways to check if a string contains a substring in Python

In addition to the above methods, you can convert a string to a list using the string.split() method and find a substring in the list using the index() method of the list.

Finding a word in an array using the index() method
fruits = 'apple, pear, banana'

print(fruits.split(', ').index('pear') != -1)

# True

Сonclusion

Python has several ways to check if a string includes a substring. In the simplest case, you can use the "in" operator. If you need the position of a substring in the string, you can use the string.find() method. If you want to do a more complex search for a substring within the string, you can use Regular Expressions.

See Also