Python String Slicing
Basic Slicing
Slicing extracts a portion of a string using string[start:end] — the character at start is included, but the character at end is not, a detail that trips up many beginners expecting an inclusive range.
Example: Basic Slicing
text = "Hello"
print(text[1:4])
Omitting Indices
Leaving out start tells Python to begin the slice from index 0, and leaving out end tells it to slice all the way to the string's final character — text[:5] and text[5:] are both common shorthand for "from the beginning" and "to the end."
Example: Omitting Indices
text = "Hello"
print(text[:3])
print(text[3:])
Step Slicing
Adding a third value — string[start:end:step] — tells Python how many characters to skip between each one it keeps; text[::2] grabs every other character across the entire string.
Example: Step Slicing
text = "abcdefgh"
print(text[::2])
Negative Slicing
Negative indices count backward from the end of the string, so text[-3:] grabs the last three characters regardless of the string's overall length — handy when you don't know exactly how long the string is in advance.
Example: Negative Slicing
text = "Hello World"
print(text[-3:])
Reversing a String
Combining a negative step with omitted start and end indices — text[::-1] — reverses an entire string in a single expression, since it tells Python to walk the string backward from end to start.
Example: Reversing a String
text = "Hello"
print(text[::-1])
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: