How do I get a substring of a string in Python?

Better Stack Team
Updated on January 26, 2023

To get a substring of a string in Python, you can use the string slicing notation, which is string[start:end], where start is the index of the first character of the substring, and end is the index of the character just after the last character of the substring. For example:

 
string = "Hello, world!"
substring = string[7:12]
print(substring)

This would output "world".

If you omit the start index, the substring will start from the beginning of the string. If you omit the end index, the substring will continue to the end of the string.

You can also use negative indices to specify the start and end indices relative to the end of the string, with -1 being the last character, -2 being the second-to-last character, and so on.

For example:

 
string = "Hello, world!"
substring = string[-5:]
print(substring)

This would also output "world"

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →