2. Slicing
A slice copies a part of a string. It uses the same bracket syntax as a list slice:
start— the index where the slice begins. Included. Default:0(the beginning).stop— the index where the slice ends. Excluded. Default: the end of the string.step— how many positions to move between characters. Default:1.
Indexes work as in the previous lesson: negative numbers count from the end. stop is the index where the slice stops before taking a character, which is why [1:4] takes indexes 1, 2 and 3 but not 4.
A slice always returns a new string; the original is never changed. Omitted parts take their default, and a negative step walks backwards:
Coming from JavaScript? String slicing is the same idea as .slice(), but the step is built in: text[::2] takes every other character and text[::-1] reverses the string.
Take a range of characters
start is included and stop is excluded. In "Python", the characters at indexes 1, 2 and 3 are y, t and h.
Print the slice of "Python" that starts at index 1 and stops at index 4.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Omit the start
When start is omitted, the slice begins at index 0.
Print the first three characters of "Python" using a slice whose start is omitted.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Omit the stop
When stop is omitted, the slice runs to the end of the string.
Print every character from index 3 to the end of "Python".
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Start from the end
A negative start counts from the end of the string.
Print the last two characters of "Python" using a slice with -2 as start and no stop.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Take every second character
step controls how many positions to move after each character. A step of 2 takes one character and skips the next one.
Create a variable named word with the value "Python", then print every second character of word, starting at index 0, using a step of 2.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Reverse a string
A negative step walks from the end towards the beginning.
Print "Python" in reverse using a step of -1 and no start or stop.
Print exactly:
Create a free account to save your progress and unlock chapter 2.