From one letter to a chunk
In the Indexing Python Strings tutorial, we learned that every character in a string has a numbered position, and s[4] fetches exactly one of them. That's great for a single letter, but pretty slow if you want the word "bread" out of "breadbox". Fetching it letter by letter would take five lookups.
Since we already know how to locate characters by index, we can go one step further and use those same numbers to manipulate whole chunks of the data at once. That's called slicing: you tell Python where to make two cuts, and everything between the cuts comes away in one piece, like slicing a loaf of bread.
Key word: a slice is a copy of part of a sequence, described by three numbers: a start, a stop, and a step. All three are optional, and that's where the fun begins.
Start and stop
The slicing syntax looks just like indexing, except you put a colon inside the square brackets: s[start:stop]. The start is the index where the slice begins, and the stop is the index where the program stops slicing. Here is the single most important fact in this tutorial:
The stop index is NOT included. The slice ends just before the stop index. word[0:5] grabs indexes 0, 1, 2, 3, and 4, but not 5.
The best way to see why is to stop thinking about the characters and start thinking about the cut positions between them, exactly like the numbered cuts on the loaf in the picture above. The cuts sit between the letters: cut 0 is before the first character, cut 1 is after it, and the last cut equals the length of the string. A slice makes one cut at start and one cut at stop, and hands you everything in between:
word = "breadbox" # cuts: 0 b 1 r 2 e 3 a 4 d 5 b 6 o 7 x 8 print(word[0:5]) # between cut 0 and cut 5 print(word[5:8]) # between cut 5 and cut 8
bread box
Bonus of the cut model: the length of a slice is just stop minus start. Cut 5 minus cut 0 is 5 characters of "bread". And the same cut, 5, is where one slice ends and the next begins, so nothing is skipped and nothing is counted twice.
Leaving out start or stop
Python automatically defaults the start position to zero unless it is told otherwise, so the start is optional. Leave out the stop and Python defaults it to the very end of the string. Leave out both and you get a copy of the whole thing:
snack = "cinnamon roll" print(snack[:8]) # no start = from the very beginning print(snack[9:]) # no stop = all the way to the end print(snack[:]) # neither = a copy of everything
cinnamon roll cinnamon roll
There is also a long-form spelling: the built-in slice(start, stop, step) function builds a reusable slice object that you can store in a variable and drop into the square brackets. It follows the exact same rules, and it works on any sequence, not just strings. Here is the program from the original tutorial, slicing a tuple of Greek letters, which shows that using 0 as the start or leaving it out entirely gives the same result:
""" This program shows how the slice defaults to zero when no start is given """ greek = ("alpha", "beta", "gamma", "delta", "epsilon", "kappa", "phi", "omega") # Using 0 as the starting point and 3 as the stopping point x = slice(0, 3) print("Using 0: " + str(greek[x])) # Using 3 as the stopping point, without a starting point y = slice(3) print("Not using 0: " + str(greek[y]))
Using 0: ('alpha', 'beta', 'gamma')
Not using 0: ('alpha', 'beta', 'gamma')
Both lines print only 'alpha', 'beta', 'gamma'. Even though "delta" sits at index 3, it does not print, because the slicing stops at the index before the stop value. Stop excluded, every time.
The step
The third number, step, tells the program how many places to count before slicing again. It's optional too (it defaults to 1, meaning take every character), and it gets its own colon: s[start:stop:step]. A step of 2 takes every other character:
secret = "bxaxgxexlxs" # every other character, starting at index 0 print(secret[::2])
bagels
The step is helpful whenever data repeats in a pattern. In this program from the original tutorial, the tuple of pastel colors gets sliced with a step of 2 to grab every other color, stopping before the last one:
""" This program slices a tuple of pastel colors, accessing every other item and stopping before the last """ pastels = ("rose gold", "teal", "lavender", "dreamsicle", "cream", "amethyst", "pearl", "coral") # Start at 0, stop before 7, take every 2nd color index = slice(0, 7, 2) print(pastels[index])
('rose gold', 'lavender', 'cream', 'pearl')
Negative slices and reversing
Remember negative indexes? They count from the back of the string, starting at -1, and they work inside slices too. s[-6:] means "the last six characters" and s[:-6] means "everything except the last six", no matter how long the string is.
The step can be negative as well. A step of -1 walks through the string backward, which gives you the most famous slice in Python: s[::-1], the one-liner that reverses a string.
loaf = "pumpernickel" print(loaf[-6:]) # the last six characters print(loaf[:-6]) # everything but the last six word = "desserts" print(word[::-1]) # step -1 walks backward
nickel pumper stressed
Nice touch: reverse "desserts" and you get "stressed". Slicing never changes the original string; it always hands you a brand new copy.
The slice machine
Time to slice some bread. Type any word or phrase and it gets laid out as a loaf: every character is a slice of bread with its index below, and the cut positions between the characters are numbered along the top. Fill in start, stop, and step (or leave any of them blank!) and watch the chosen chunk butter up and lift away. The exact Python expression and its result appear underneath.
Slice Machine
Your string
Try a classic
Fill in any of start, stop, and step, or leave them blank. Blank start means 0, blank stop means the end, blank step means 1.
Try this: set start to 2 and stop to 99. Then try a negative start like -3 with no stop. The machine follows Python's real rules, including the surprising one in the next section.
Why slices never crash
Indexing is strict: ask for s[99] in a 9-character string and Python stops your whole program with an IndexError. Slicing is the chill sibling. If your cuts land past the end of the loaf, Python just quietly clamps them back to the edge of the string and gives you whatever actually exists there, even if that's an empty string:
Slicing: clamps gracefully
s = "sourdough" print(s[2:99]) print(s[99:])
urdough
Indexing: crashes
s = "sourdough" print(s[99])
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(s[99])
IndexError: string index out of range
On the left, s[2:99] just returns everything from cut 2 to the end, and s[99:] returns an empty string (that blank second row in the console). On the right, the very same 99 used as a plain index brings the program down. If you only remember one contrast from this page, make it this one.
Practice challenges
These challenge scenarios come from the original tutorial. Imagine you are a Performing Arts Director writing an article on the most relevant artists of 2020. The tuple below lists 18 artists in a repeating pattern: Vocal Artist, Actor, Director, over and over. All three challenges slice this same tuple (the slice machine above makes a great scratchpad for counting):
artists = ("Beyonce", "Lupita Nyong'o", "Judd Apatow", "Post Malone", "Michael B. Jordan", "Tim Burton", "Shawn Mendes", "Daniel Kaluuya", "George Lucas", "Brendon Urie", "Zendaya", "Kenya Barrris", "Lady Gaga", "Tom Holland", "Steven Spielberg", "Jack White", "Millie Bobby Brown", "Ava DuVernay")
Vocabulary check
Before touching the artists, warm up. In your own words, define the three slice parameters: start, stop, and step. What does each one default to when you leave it out?
The start parameter is the index where slicing begins; it defaults to 0. The stop parameter is the index where slicing ends, and it is not included: the slice stops just before it. It defaults to the end of the sequence. The step parameter is how many places to count before slicing again; it defaults to 1, and a negative step walks backward.
List 1: only the actors
Fill in the correct parameters so that only the actors' names print. Remember the pattern repeats Vocal Artist, Actor, Director, so the first actor is "Lupita Nyong'o". Your output should be:
# actors = artists[?:?:?] print(actors) # ("Lupita Nyong'o", 'Michael B. Jordan', 'Daniel Kaluuya', # 'Zendaya', 'Tom Holland', 'Millie Bobby Brown')
The actors sit at indexes 1, 4, 7, 10, 13, and 16: start at 1 and step by 3. So artists[1:18:3] works, and since 18 is the whole length you can leave the stop out: artists[1::3]. The long spelling is slice(1, 18, 3).
actors = artists[1::3] # start 1, to the end, every 3rd print(actors)
("Lupita Nyong'o", 'Michael B. Jordan', 'Daniel Kaluuya', 'Zendaya', 'Tom Holland', 'Millie Bobby Brown')
List 2: the second half
Alter the slice named second_half so that only the second half of all 18 artists prints. The output should begin with 'Brendon Urie' and end with 'Ava DuVernay'.
18 artists means the second half starts at index 9 (indexes 0 through 8 are the first half). artists[9:18], or simply artists[9:], or slice(9, 18).
second_half = artists[9:] # from index 9 to the end print(second_half)
('Brendon Urie', 'Zendaya', 'Kenya Barrris', 'Lady Gaga', 'Tom Holland', 'Steven Spielberg', 'Jack White', 'Millie Bobby Brown', 'Ava DuVernay')
List 3: trim the bookends
Beyonce has become a fashion designer and Ava DuVernay is now a screenwriter, so both need to come off the list. Alter the slice named bookends so the first and last artists are removed and everyone else prints. Can you do it in a way that would still work if the tuple grew longer?
artists[1:17] (or slice(1, 17)) does it: start at index 1 to skip Beyonce, and stop at 17 so index 17, Ava DuVernay, is excluded. Even better is artists[1:-1], which trims one item off each end of any length of list. Stop excluded strikes again!
bookends = artists[1:-1] # skip the first and the last print(bookends)
("Lupita Nyong'o", 'Judd Apatow', 'Post Malone', 'Michael B. Jordan', 'Tim Burton', 'Shawn Mendes', 'Daniel Kaluuya', 'George Lucas', 'Brendon Urie', 'Zendaya', 'Kenya Barrris', 'Lady Gaga', 'Tom Holland', 'Steven Spielberg', 'Jack White', 'Millie Bobby Brown')
Quick quiz
1. With s = "python", what does print(s[1:4]) output?
2. With word = "notebook", what does print(word[:4]) output?
3. With s = "toast", what does print(s[0:99]) do?
Keep learning Python
You can now cut any chunk you want out of a string: front, back, every other character, or the whole thing in reverse. Keep the momentum going with more string skills and full Python courses.