How to Get Part of a String in Python 3 (substring or substr)

To get a part of a Python string, you can use the bracket notation:

letters = 'abcdefg'
print(letters[0:3])

Where the notation is [from:to].

The result of the above code is:

abc

The numbers are indexes into the string. The result string contains the character at the from index, but does not contain the character at the to index.

Here's another example:

letters = 'abcdefg'
print(letters[2:5])

the result is:

cde

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.