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

ID : 300

viewed : 190

Tags : pythonstringsubstringpython





Top 5 Answer for How do I get a substring of a string in Python?

vote vote

97

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

vote vote

82

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:

some_string[::-1] 

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.

vote vote

76

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] 
vote vote

64

A common way to achieve this is by string slicing.

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

vote vote

56

One example seems to be missing here: full (shallow) copy.

>>> x = "Hello World!" >>> x 'Hello World!' >>> x[:] 'Hello World!' >>> x==x[:] True >>> 

This is a common idiom for creating a copy of sequence types (not of interned strings), [:]. Shallow copies a list, see Python list slice syntax used for no obvious reason.

Top 3 video Explaining How do I get a substring of a string in Python?







Related QUESTION?