A substring is a sequence of characters that are part of an original string. In Python, substrings can be obtained by using the slicing feature on a string variable. A slice can be made in a specific position within the string or it can be made at the default index.
A slice is made by using the open
[ and closed
] square brackets next to a string variable. Inside the brackets, the position can be given:
startdefaults to 0 and gives the initial position the slice will start from.
enddefaults to -1 and is the position where the slicing will end.
stepdefaults to 1 and indicates the number of steps to take in between indexes.
The following examples show different ways of obtaining substrings from an original string
name = "Code Ninja"
Retrieving Single Characters
When only one index is specified, a single character is returned. An index of
0 retrieves the first character of the string:
print(name)# Output: C
Negative numbers work on the string backwards. For example, index
-1 retrieves the last character of the string:
print(name[-1])# Output: a
Negative Start Index
Using a negative start index (
-n) with the default end value accesses the last
n characters of the string. The following gives access to the last three characters of the string:
print(name[-3:])# Output: nja
To specify only an end index, use
n is the ending position. This will return the first
print(name[:4])# Output: Code
Negative Step Value
Given a negative step value, returns the results backward:
reversed = name[::-2]print(reversed)# Output: anNeo
in keyword can be used to check for a specific substring, like in the example below:
print('de' in name)# Output: True
The string method
.find() can also be used to find a subset. It returns the index of the first occurrence of the substring. If the substring is not found, it returns
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.