>>> examplestring = 'Hello World'So far this has already been covered. But the index in the square brackets need not be a single number for a single element.
>>> examplestring[0]
'H'
>>> examplelist = ['This', 'is', 'a', 'list', 'of', 'strings']
>>> examplelist[-2]
'of'
>>> exampletuple = (20, 40, 60, 80, 100, 120)
>>> exampletuple[2]
60
>>>
Slicing is selecting a number of adjacent elements in the sequence, giving the indexes of the range you want, with a colon : to separate start point from end point. For example:
>>> print(examplestring[2:7])As you can tell, it starts at the starting point but the last element given is one short of the stated finishing point. In the first example with the print(examplestring[2:7]), it gives the characters at the indices 2, 3, 4, 5 & 6, not 7
llo W
>>> print (examplelist[1:3])
['is', 'a']
>>> print (exampletuple[3:5])
(80, 100)
>>>
Also the slice returned is the same type as the original sequence, so a slice of a string returns a string, a slice of a list returns a list etc.
If no index is given before the colon, the slice starts at the beginning
>>> print (examplestring[:8])Hello Woand if there is no index given after the colon, the slice goes through to the end
>>> print (exampletuple[3:])If you really wanted to, you could simply have a colon without indices, and it would return the whole sequence, though I am not sure if this is of practical use.
(80, 100, 120)
>>>
>>> print (examplelist[:])Slices can accept -1 as the end element and negative indices step backwards from the end of a sequence. So if you don't know how long a sequence is but you want the last three elements you can do
['This', 'is', 'a', 'list', 'of', 'strings']
>>>
>>> print (exampletuple[-3:])
(80, 100, 120)
>>>
All of these slices can be assigned to new variables, or even replace the existing variable with an assignment statement.
No comments:
Post a Comment