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?
That's pretty simple:
Substr() normally (i.e. PHP and Perl) works this way:
So the parameters are
beginning
andLENGTH
.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
I would like to add two points to the discussion:
You can use
None
instead on an empty space to specify "from the start" or "to the end":This is particularly helpful in functions, where you can't provide an empty space as an argument:
Python has slice objects:
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:
The ability to step forwards and backwards through the string maintains consistency with being able to array slice from the start or end.
Maybe I missed it, but I couldn't find a complete answer on this page to the original question(s) because variables are not further discussed here. So I had to go on searching.
Since I'm not yet allowed to comment, let me add my conclusion here. I'm sure I was not the only one interested in it when accessing this page:
If you leave the first part, you get
And if you left the : in the middle as well you got the simplest substring, which would be the 5th character (count starting with 0, so it's the blank in this case):
Using hardcoded indexes itself can be a mess.
In order to avoid that, Python offers a built-in object
slice()
.If we want to know how many money I got left.
Normal solution:
Using slices:
Using slice you gain readability.