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

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

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

Just for completeness as nobody else has mentioned it. The third parameter to an array slice is a step. So reversing a string is as simple as:


Or selecting alternate characters would be:

"H-e-l-l-o- -W-o-r-l-d"[::2] # outputs "Hello World"

The ability to step forwards and backwards through the string maintains consistency with being able to array slice from the start or end.

Substr() normally (i.e. PHP and Perl) works this way:

s = Substr(s, beginning, LENGTH)

So the parameters are beginning and LENGTH.

But Python’s behaviour is different; it expects beginning and one after END (!). This is difficult to spot by beginners. So the correct replacement for Substr(s, beginning, LENGTH) is

s = s[ beginning : beginning + LENGTH]

A common way to achieve this is by string slicing.

MyString[a:b] gives you a substring from index a to (b – 1).

Leave a Comment