← Back to Python Course | Chapter 5: Strings | Lesson 3 of 6

Python String Slicing

Slicing is cutting out a piece of a string, like cutting a slice from a loaf of bread. You say where to start and where to stop.
Syntax
python
string[start:stop]
string[start:stop:step]
string[::-1]

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

python
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

python
text = "Hello"
print(text[:3])  # start omitted, so it begins at index 0
print(text[3:])  # end omitted, so it goes to the last character

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

python
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

python
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

python
text = "Hello"
print(text[::-1])
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting that the stop index is excluded, so "Python"[0:2] gives "Py" and not "Pyt".
  2. Using a negative step without swapping bounds, as in s[0:5:-1], which returns an empty string; use s[::-1] to reverse.
  3. Expecting slicing out of range to raise an error, when "abc"[1:100] quietly returns "bc" while "abc"[100] raises IndexError.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.