Python: Slicing

Being able to understand slicing is very useful, not just for Python, but for data libraries like Pandas. Slicing allows you to specify an index range from which the data is returned.

name = "Barnaby"
print(name[:3]) # returns Bar (index 0, 1 and 2)
print(name[0:3]) #returns the same result, explicitly stated to start at 0 to go up to (but not including) index 3.

print(name[3:]) # is naby 

Slicing can also use negative indexing, which starts at the end of the variable:

print(name[-1]) # is b
print(name[-1:2]) # is nothing, as index 2 is before -1
print(name[-3:]) # is aby
print(name[-3:-1]) # is ab
print(name[0::2]) # outputs Bray, this starts at index 0, and skips 2 indexes
print(name[0:7:2]) # same as above, Bray. It starts at index 0, goes to index 7 and skips every other index (2).

About Author /

Leave a Comment

Your email address will not be published.

Start typing and press Enter to search