8.3. Taking a Slice¶
In addition to accessing single characters in a string, we can also use bracket notation to return multiple characters. This smaller set of characters is called a substring of the original.
A substring is also called a slice of the original string. Selecting a slice is similar to selecting a character, and the syntax is:
some_string[start_index : end_index]
With this format, Python returns all of the characters from the
value up to but NOT including the
1 2 3 4
alphabet = 'abcdefghijklmnopqrstuvwxyz' substring = alphabet[2:5] print(substring)
Since we start counting at 0, the character at index value 2 is
and the character at index 5 is
'f'. However, note that
NOT included in the slice.
If we leave out the first index (before the colon), the slice starts at the beginning of the string. If we leave out the second index, the slice goes to the end of the string.
1 2 3
fruit = "cucumber" print(fruit[:3]) print(fruit[3:])
What do you think
8.3.1. Saving Substrings¶
In the examples above, we simply print a substring to the
print(fruit[:3]). This works because when we use brackets to
return part of a string, we actually create a new string.
This new string is a piece of data, and we can perform operations on it like any other string. The
fruit[:3] returns the string
'cuc', so the
'cuc' again, we will need
to take another slice from
fruit, or save the string in a new variable.
Instead of creating, using, then losing a new string, we can assign it to a variable whenever we use bracket notation.
1 2 3 4 5
vegetable = "carrot" top_half = vegetable[0:3] end_piece = vegetable[-1] print(top_half, end_piece, vegetable)
car t carrot
By assigning the substrings
't' to variables, we can use
those strings elsewhere in the program.
Notice that taking two slices from the string
did NOT change the string itself. We will explore this idea in the next
8.3.2. Check Your Understanding¶
language = 'Python', what does