Sliced Py- Cheat sheet for Python Slicing

I'm constantly using slicing in my Python scripts, but I am also constantly scratching my head about exactly where to put the little colon to get the slice that I'm after.

After consulting the stackoverflow gurus I wrote a little cheat sheet using a string as an example.  


foo = "Monty Python's Flying Circus"

#Print the middle of foo- slice from the 7th-1 character end at the 15th-1 character
print foo[6:14]

#Use a slice to get the first six characters
print foo[:6]
#>>> Monty

#Slice after the first six characters of foo
print foo[6:]
#>>> Python's Flying Circus

#Print everthing in foo
print foo[:]
#>>> Monty Python's Flying Circus

#Every second character
print foo[0:27:2]
#>>> MnyPto' ligCru

#The last character of foo
print foo[-1]
#>>> s

#The last two characters of foo
print foo[-2:]
#>>> us

#Everything but the last seven charachers of foo
print foo[:-7]
#>>> Monty Python's Flying

Comments

Popular posts from this blog

Calling Python from Substance Painter

A Quick Checkin- Clion, Unreal and Mac