59 – Idiomatic sequence slicing#
There are five slicing patterns that are fairly common and that have simple interpretations, and that’s what an idiom is: a piece of code that you recognise for its meaning as a whole.
You should be able to interpret these five slicing idioms automatically without having to think:
[:n]– firstnchars[n:]– after firstnchars[:-n]– without lastnchars[-n:]– lastnchars[::-1]– reversed (but the built-inreversedis usually preferred)
string = "Slicing is easy!"
print(string[:4]) # Slic
print(string[4:]) # ing is easy!
print(string[:-4]) # Slicing is e
print(string[-4:]) # asy!
print(string[::-1]) # !ysae si gnicilS
Further reading: