3. Strings
3.2 Slicing
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
Slicing cuts a piece out of a string, like cutting a slice of pizza.
- [start:stop] takes from start up to, but not including, stop.
- Leave start empty to begin at the beginning.
- [::-1] reads it backwards.
Thumb rule: The stop number is never included in the slice.
Watch it run · 1
print("PYTHON"[0:2])PY
Watch it run · 2
print("PYTHON"[::-1])NOHTYP
A slice cuts out part of a string: value[start:stop]. The start position is included; the stop position is not.
date = "2026-11-24"date[:4]→"2026"(from the start, up to index 4)date[5:7]→"11"date[8:]→"24"(from index 8 to the end)date[-2:]→"24"(the last two characters)
Slicing is handy for fixed-format text such as dates, codes and file names. Unlike indexing, a slice that runs past the end doesn’t raise an error; it just stops at the end.
Think of cut lines between characters
[0:4]cuts before index 0 and before index 4- So you get characters 0, 1, 2 and 3
- Length of the slice = stop − start = 4
value[start:stop] never includes stop. To get the first 4 characters, write [:4], not [:3].
How it fits together
- "2026-11-24"
- [:4] → 2026
- [5:7] → 11
Step through the code
Python
partition_key = "2026-11-24"print(partition_key[:4])print(partition_key[5:7])
Output
2026 11
Practice in Python ✓ Solved
Print the YYYY-MM part of partition_key.
Expected output
2025-03
Reference solution
partition_key = "2025-03-18"
print(partition_key[:7])
Question 1 · Easy
word = "pandas". What is word[:3]?
Question 2 · Medium
file = "sales_2025.csv". What is file[-4:]?
Question 3 · Hard
code = "AB12". What is code[1:10]?
Key takeaways
Slices include the start and stop before the end index.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in