In Python, a substring is a sequence of characters taken from a larger string. You can extract a substring with string slicing, check whether a substring exists with the in operator, or find its position with methods such as find() and index(). This tutorial first explains slicing and then covers common substring-search operations.
Python substring: extracting text with string slicing
Python does not have a separate substring data type. A substring produced from another string is itself a Python str. To extract characters between specific positions, use string slicing.
Python substring slicing syntax with start and stop indices
The syntax for slicing a string to get the substring defined by a specific start index and stop index is given in the following.
mystring[start\:stop]
where the slicing happens on mystring string from start index to stop-1 index. start and stop are indices of characters in the string. Please note that the index of characters in the string start from 0.
start and stop are optional and can accept any integer, both positive and negative.
If we do not provide start, the slicing of the string defaults to the beginning of the given string. In other words default value of start is 0.
If we do not provide stop, the slicing of the string defaults to till the end of the string. In other words default value of stop is length of the string.
The stop index is exclusive. For example, text[2:7] includes the character at index 2 but does not include the character at index 7. This exclusive-stop rule is important when calculating the required substring boundaries.
Python substring slicing examples with positive, omitted, and negative indices
The following examples show how start and stop affect the substring returned by slicing. They cover positive indices, omitted indices, and negative indices counted from the end of the string.
1. Python substring with specific start and stop indices
In this example, we shall initialize a string, and find the substring that starts from a specific start position and ends at specific end position.
Python Program
string = 'tutorialkart'
start = 2
stop = 7
#find substring
substring = string[start\:stop]
print(substring)
Run the above program.
toria
The slice starts at index 2 and stops before index 7, so the characters at indices 2 through 6 form the substring.
2. Python substring from the beginning to a stop index
In this example, we shall initialize a string, and find the substring by specifying only stop position. We are leaving the start parameter empty. So, the slicing of string should happen from beginning of the string. Let us see.
Python Program
string = 'tutorialkart'
stop = 7
#find substring
substring = string[:stop]
print(substring)
Run the above program.
tutoria
Because the start index is omitted, Python starts at the first character and returns everything before index 7.
3. Python substring from a start index to the end
In this example, we specify only the start position. The stop index is omitted, so Python slices from the specified start index through the end of the string.
Python Program
string = 'tutorialkart'
start = 5
#find substring
substring = string[start:]
print(substring)
Run the above program.
ialkart
4. Python substring with both start and stop omitted
Let us not provide any start or stop positions. We know that if start is not provided, slicing happens from starting of the string. Also, if no stop position is provided, the slicing happens till the end of the string. There if we do not provide any start or stop positions, the resulting substring will be just a copy of the original string.
Python Program
string = 'tutorialkart'
#find substring
substring = string[:]
print(substring)
Run the above program.
tutorialkart
5. Python substring with a negative stop index
We can provide a negative number for stop parameter. Negative position mean that you have to consider the end of the string to get to calculate the position.
In the following example, we have taken stop as -2. So, resulting stop would be len(string)-2.
Python Program
string = 'tutorialkart'
start = 5
stop = -2
#find substring
substring = string[start\:stop]
print(substring)
Run the above program.
ialka
A stop value of -2 refers to a position two characters back from the end. As with a positive stop index, the character at the stop position itself is excluded.
6. Python substring with a negative start index
As discussed in the previous example, the same explanation holds for the negative start value to find the substring.
start = -10 means start = len(string)-10.
Python Program
string = 'tutorialkart'
start = -10
stop = 10
#find substring
substring = string[start\:stop]
print(substring)
Run the above program.
torialka
7. Python substring with both negative start and stop indices
In this example, we provide negative values for both start and stop positions.
Python Program
string = 'tutorialkart'
start = -10
stop = -2
#find substring
substring = string[start\:stop]
print(substring)
Run the above program.
torialka
Check if a Python string contains a substring using in
If you only need to know whether some text occurs inside a string, use the in operator. It returns True when the substring is present and False otherwise.
substring in string
text = 'Learn Python programming'
print('Python' in text)
print('Java' in text)
Output
True
False
Use in when you need a yes-or-no membership test rather than the position of the matching substring.
Find the index of a substring in Python with find()
The string find() method searches for a substring and returns the index where its first occurrence begins. If the substring is not found, find() returns -1.
string.find(substring)
string.find(substring, start, end)
text = 'Python substring example'
position = text.find('substring')
missing = text.find('Java')
print(position)
print(missing)
Output
7
-1
The optional start and end arguments restrict the search to part of the string. The returned value is still an index relative to the original string.
Python find() versus index() for substring searches
find() and index() both return the starting index of the first matching substring. Their main difference is what happens when there is no match: find() returns -1, while index() raises a ValueError.
text = 'Python programming'
print(text.find('Java'))
try:
print(text.index('Java'))
except ValueError:
print('Substring not found')
Output
-1
Substring not found
Use find() when a missing substring is an expected possibility that you want to test with -1. Use index() when the substring is expected to exist and a missing value should be treated as an error.
Find all occurrences of a substring in a Python string
find() returns only one position per call. To collect every occurrence, repeatedly search from the position immediately after the previous match.
text = 'banana'
substring = 'ana'
positions = []
start = 0
while True:
position = text.find(substring, start)
if position == -1:
break
positions.append(position)
start = position + 1
print(positions)
Output
[1, 3]
Advancing by one character allows this example to include overlapping matches. If overlapping occurrences should not count, advance by len(substring) instead.
Case-insensitive substring search in Python
Python substring searches are case-sensitive. For a case-insensitive comparison, normalize both the source string and the substring before testing them. casefold() is intended for caseless string comparisons.
text = 'Learn PYTHON Programming'
substring = 'python'
found = substring.casefold() in text.casefold()
print(found)
Output
True
Check whether a Python string contains any substring from a list
When you have several candidate substrings, combine the in operator with any(). The result is True as soon as one candidate is found in the string.
text = 'Python string operations'
substrings = ['Java', 'string', 'database']
found = any(item in text for item in substrings)
print(found)
Output
True
Find Python substrings with regular expressions when the pattern varies
Use ordinary string methods for fixed text. When the substring is described by a pattern rather than an exact sequence of characters, Python’s re module can be more suitable. For example, the following code searches for the word Python followed by one or more digits.
import re
text = 'Course version Python312 is available'
match = re.search(r'Python\d+', text)
if match:
print(match.group())
Output
Python312
Regular expressions are not necessary when you are searching for a known literal substring. In those cases, in, find(), or index() is usually simpler.
Choosing the right Python substring operation
- Use
string[start:stop]when you already know the character positions and want to extract part of a string. - Use
substring in stringwhen you only need to check whether a substring exists. - Use
string.find(substring)when you need the position and want-1for no match. - Use
string.index(substring)when you need the position and a missing substring should raise an error. - Use repeated
find()calls when you need the positions of multiple occurrences. - Normalize strings with
casefold()when the substring comparison should ignore letter case. - Use the
remodule when you are searching for a pattern rather than fixed text.
Python substring slicing and search summary
In this Python Tutorial, we learned how to find the substring of a string using slicing mechanism.
String slicing extracts characters between known positions, while in, find(), and index() search for text by value. We also covered negative slicing indices, finding all substring occurrences, case-insensitive searches, checking a list of candidate substrings, and using regular expressions for pattern-based searches.
TutorialKart.com