Published Mar 6, 2022Updated Mar 18, 2023
Contribute to Docs

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:

  • start defaults to 0 and gives the initial position the slice will start from.
  • end defaults to -1 and is the position where the slicing will end.
  • step defaults 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.

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:

# Output: C

Negative numbers work on the string backwards. For example, index -1 retrieves the last character of the string:

# 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:

# Output: nja

End Index

To specify only an end index, use [:n], where n is the ending position. This will return the first n characters.

# Output: Code

Negative Step Value

Given a negative step value, returns the results backward:

reversed = name[::-2]
# Output: anNeo

Keyword in

The in keyword can be used to check for a specific substring, like in the example below:

print('de' in name)
# Output: True

.find() Method

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 -1.

Visit us
Hide code
Hide output
Hide output

All contributors

Looking to contribute?

Learn Python on Codecademy