How do I get a substring of a string in Python?

>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'

Python calls this concept “slicing” and it works on more than just strings. Take a look here for a comprehensive introduction.

Leave a Comment