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.
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
The slice operation can also be applied to a list
my_list = [1, 99, 10, ‘Bill’, ‘a’]
my_list[1:4] returns the list [99, 10, ‘Bill’]. The element my_list is not included.