Joan Venge Joan Venge - 3 months ago 8
Python Question

Is there a way to substring a string in Python?

Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?

Maybe like

myString[2:end]
?

If leaving the second part means 'till the end', if you leave the first part, does it start from the start?

Answer
>>> 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.