Slices of every shape
Every slice here is a new string. The original s is never changed.
Every character in a string has a position number, starting at 0, and you can also count from the end with negative numbers. A slice s[start:stop:step] cuts out a piece of the string, never fails for out-of-range numbers, and gives you a new string.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Given word = "Hectal", print its first three letters, its last three letters and the word reversed.
Given s = "0123456789", print every third character starting from index 1.
Given email = "user@example.com", find the position of @ with email.find("@") (find gives the index of the first match; Topic 3.2 teaches it) and print the part after it and the part before it.
Explain it without notes
Why do Python indexes start at 0, and what is the last valid index of a string?
What does s[a:b] return, and why is b excluded?
Explain how s[::-1] reverses a string, and what changes about the defaults when the step is negative.
What is the difference between s[10] and s[10:11] when s is shorter than 10 characters?
Expected output
s[2:5] -> cde
s[:3] -> abc
s[7:] -> hij
s[-3:] -> hij
s[::2] -> acegi
s[1::3] -> beh
s[::-1] -> jihgfedcba
s[8:2:-2] -> ige
s[3:100] -> defghij
s[50:60] -> ''
copy equals s: True