PY-101 ยท Strings in depth
Slicing patterns
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
A slice takes part of a string or list with [start:stop:step]. Any part can be left out: s[:3] is the first three, s[-4:] the last four, s[::2] every second item and s[::-1] the whole thing reversed. Slicing never raises an error for out-of-range positions; it just returns what exists.
- Take the first or last n items
- Skip with a step
- Reverse with [::-1]
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
card = "4111222233334242"print("*" * (len(card) - 4) + card[-4:])word = "Python"print(word[:3], word[3:], word[::2], word[::-1])days = list(range(1, 11))print("Last 3:", days[-3:])print("Page 2:", days[5:10])
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
************4242
Pyt hon Pto nohtyP
Last 3: [8, 9, 10]
Page 2: [6, 7, 8, 9, 10] ๐ฏ Write is_palindrome(word) that returns True when the word reads the same backwards (ignore capital letters). Print is_palindrome("Level").
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
w = word.lower(); return w == w[::-1]
- The problemA payment page must show a card number as "************4242". You need the last four digits and stars for the rest: one slice and a little maths.
- The Python idea
s[start:stop:step]A slice takes part of a string or list with [start:stop:step]. - In real lifePaging through search results is a slice: items[(page - 1) * size : page * size].
Start with a question
A payment page must show a card number as "************4242". You need the last four digits and stars for the rest: one slice and a little maths.
Previews, masking, pagination and "last 7 days" views are all slices.
Explain it like I'm 10
Slicing is cutting a piece of a cake: say where to start, where to stop, and whether to take every slice or every other one.
The technical explanation
start is included, stop is not. Missing start means the beginning; missing stop means the end.
Negative numbers count from the end: s[-3:] is the last three characters.
A negative step walks backwards, so s[::-1] reverses.
Syntax
s[start:stop:step]
s[:n] s[-n:] s[::2] s[::-1] Real-world scenario
Paging through search results is a slice: items[(page - 1) * size : page * size].
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Regular expressions basics โQuestions people ask
How do I reverse a string in Python?
Use a slice with step -1: text[::-1]. For a list you can also call items.reverse() to reverse it in place.
Why does slicing not raise IndexError?
Slices are clamped to the sequence length, so they return whatever part exists. Single-item indexing like s[10] does raise IndexError.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner How do I reverse a string in Python?
Use a slice with step -1: text[::-1]. For a list you can also call items.reverse() to reverse it in place.
beginner Why does slicing not raise IndexError?
Slices are clamped to the sequence length, so they return whatever part exists. Single-item indexing like s[10] does raise IndexError.
intermediate "hello"[1:4]?
"ell". Positions 1, 2 and 3.
intermediate "hello"[-2:]?
"lo". The last two characters.
Quick revision
Remember
- Take the first or last n items
- Skip with a step
- Reverse with [::-1]
- Slices copy.
backup = items[:]gives you a new list, so changing backup does not change items.
Syntax
s[start:stop:step]
s[:n] s[-n:] s[::2] s[::-1] Official documentation
- Common sequence operations (docs.python.org)