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 going up to but not including the character at index m.
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?.
Itβs important to note that slicing a string does not change the original string (remember - strings are immutable, you can make a copy but once a string is created, it never changes). So if you want to do something with a slice of a string, you can either embed it in an expression, or you can save it to a variable, as in the example below, where we take slices of two strings, concatenate them with a hyphen in between and assign that to a new variable. Note that the original strings have not been changed.
Subsection9.6.2List Slices
The slice operation we saw with strings also works 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. Before running the code below, complete the comments on lines 2-5 by adding your predictions about what will be printed.
Subsection9.6.3Tuple 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 a 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 a new tuple.
The observant student might notice that the code above appears to modify the tuple assigned to the variable julia. Didnβt we say that tuples are immutable? Whatβs happening on line 7 in the above example is that a new tuple is being created, using parts of the old tuple and some new information, and then it is being assigned back to the reference variable julia. This very subtle difference (which unfortunately does not really show in CodeLens) becomes important when we start passing sequences as function parameters later in this chapter.
Check your understanding
Checkpoint9.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.