Section 8.6 The Slice Operator
A substring of a string is called a slice. Selecting a slice is similar to selecting a character:
The slice
operator [n:m]
returns the part of the string starting with the character at index n and go up to but not including the character at index m. Or with normal counting from 1, this is the (n+1)st character up to and including the mth character.
If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string.
What do you think fruit[:]
means?
Subsection 8.6.1 List Slices
The slice operation we saw with strings also work on lists. Remember that the first index is the starting point for the slice and the second number is one index past the end of the slice (up to but not including that element). Recall also that if you omit the first index (before the colon), the slice starts at the beginning of the sequence. If you omit the second index, the slice goes to the end of the sequence.
Subsection 8.6.2 Tuple Slices
We can’t modify the elements of a tuple, but we can make a variable reference a new tuple holding different information. Thankfully we can also use the slice operation on tuples as well as strings and lists. To construct the new tuple, we can slice parts of the old tuple and join up the bits to make the new tuple. So julia
has a new recent film, and we might want to change her tuple. We can easily slice off the parts we want and concatenate them with the new tuple.
Check your understanding
Checkpoint 8.6.1.
What is printed by the following statements?
s = "python rocks"
print(s[3:8])
python
That would be s[0:6].
rocks
That would be s[7:].
hon r
Yes, start with the character at index 3 and go up to but not include the character at index 8.
Error, you cannot have two numbers inside the [ ].
This is called slicing, not indexing. It requires a start and an end.
Checkpoint 8.6.2.
What is printed by the following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[4:])
[ [ ], 3.14, False]
Yes, the slice starts at index 4 and goes up to and including the last item.
[ [ ], 3.14]
By leaving out the upper bound on the slice, we go up to and including the last item.
[ [56, 57, "dog"], [ ], 3.14, False]
Index values start at 0.
Checkpoint 8.6.3.
What is printed by the following statements?
L = [0.34, '6', 'SI106', 'Python', -2]
print(len(L[1:-1]))
2
The list begins with the second item of L and includes everything up to but not including the last item.
3
Yes, there are 3 items in this list.
4
The list begins with the second item of L and includes everything up to but not including the last item.
5
The list begins with the second item of L and includes everything up to but not including the last item.
Checkpoint 8.6.4.
Create a new list using the 9th through 12th elements (four items in all) of new_lst
and assign it to the variable sub_lst
.
You have attempted
of
activities on this page.