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!
s = "super turtle"
print(s[:4])
print(s[4:])
s = "super turtle"
print(s[0:6])
s = "super turtle"
print(s[0:len(s)])
s = "super turtle"
print(s[7:len(s)])
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.
s = "super turtle"
print(s[s.find("t"):len(s)])
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.
s = "super turtle"
print(s[-1])
s = "super turtle"
print(s[-2])
s = "super turtle"
print(s[-2:])
s = "super turtle"
print(s[:-2])