String and list slicing
We’ve already learned about string and list indexing. Now we’re going to look at slicing.
Indexing isolated one element at a time. Slicing isolates 0 or more elements.
The syntax is: variable[begin:end]
where begin
is inclusive and end
is exclusive.
Both begin
and end
are optional — if they are left out, this means “go from the beginning until … “ or “go from this index until the end”.
Let’s play around with this!
This technique becomes much more powerful when we combine it with the string find
method.
str.find(value)
returns the lowest index that the element occurs at and -1 if it doesn’t.
Slicing works exactly the same with lists as it does with strings!
Using negative numbers
Python lets us access indices using negative numbers as well.
-1 maps to the last index, -2 to the second to last, etc.