How do I get a substring of a string in Python?
Is there a way to substring a string in Python, to get a new string from the third character to the end of the string?
If leaving the second part means 'till the end', and if you leave the first part, does it start from the start?
>>> 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.
Read more... Read less...
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
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).
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.
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?
Yes, this actually works if you assign, or bind, the name,
end, to constant singleton,
>>> end = None >>> myString = '1234567890' >>> myString[2:end] '34567890'
Slice notation has 3 important arguments:
Their defaults when not given are
None - but we can pass them explicitly:
>>> stop = step = None >>> start = 2 >>> myString[start:stop:step] '34567890'
If leaving the second part means 'till the end', if you leave the first part, does it start from the start?
Yes, for example:
>>> start = None >>> stop = 2 >>> myString[start:stop:step] '12'
Note that we include start in the slice, but we only go up to, and not including, stop.
When step is
None, by default the slice uses
1 for the step. If you step with a negative integer, Python is smart enough to go from the end to the beginning.
>>> myString[::-1] '0987654321'
I explain slice notation in great detail in my answer to Explain slice notation Question.