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"

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github