Python — Strings (Part 2)
Slicing
You can return a range of characters by using the slice syntax.
Get Sithila Sihan Somaratne’s stories in your inbox
Join Medium for free to get updates from this writer.
Specify the start index and the end index, separated by a colon, to return a part of the string.
s = "Hello, World!"
print(s[3:5]) # loThe above code gets the characters from position 2 to position 5 (not included).
Note: The first character has index 0.
Slice From the Start
By leaving out the start index, the range will start at the first character:
s = "Hello, World!"
print(s[:5]) # HelloThe above code gets the characters from the start to position 5 (not included).
Slice To the End
By leaving out the end index, the range will go to the end:
s = "Hello, World!"
print(s[7:]) # World! (note, not " World!" that would be s[6:])The above code gets the characters from position 2, and all the way to the end.
Negative Indexing
Use negative indexes to start the slice from the end of the string:
s = "Hello, World!"
print(s[-4:-2]) # rlThe above code gets the characters from: “r” in “World!” (position -4) to, but not included: “d” in “World!” (position -2).





