The slicing operation in strings allows one to extract a section of a string. It is a very useful operation (especially since strings are immutable). The operation my_data[a:b] returns the elements from index a through index b-1. The element my_data[b] is not included! This confuses not only beginners, but Python programmer who do not routinely use the slicing operation.
Example 1
book_title = ‘Python Programming for Beginners’
slice [1:4] returns the string starting at index 1, and ending at index 3. The 4th character is not included. Hence,
- book_title[1:4] returns the string yth
- book_title[0:5] returns the string Pytho
Example 2
The slice operation can also be applied to a list
my_list = [1, 99, 10, ‘Bill’, ‘a’]
index | 0 | 1 | 2 | 3 | 4 |
my_list | 1 | 99 | 10 | ‘Bill’ | ‘a’ |
my_list[1:4] returns the list [99, 10, ‘Bill’]. The element my_list[4] is not included.