How to substring a string Python from a specific index in Python?
Solution 1:
>>> val = 's2*20'
>>> val.split('*')[1]
'20'
Depending on what you want, you may want to check for '*'
inside your string, or just taking everything after the first occurrence of '*'
, but hard to guess without more info. This might be a plausible scenario:
>>> def rest(s):
... return s.split('*',1) if '*' in s else s
...
>>> rest('hi')
'hi'
>>> rest('hi there * wazzup * man')
['hi there ', ' wazzup * man']
Edit: as pointed out in the comment by @Jon (no, not Skeet), using partition
is better in every way.
>>> val = 's2*20'
>>> val.partition('*')[2]
'20'
>>> val = 's2-20'
>>> val.partition('*')[2]
''
It's smoother and performs surprisingly good - in fact a lot better than split
:
>>> import timeit
>>> timeit.timeit('"s2*20".split("*")')
0.22846507105495942
>>> timeit.timeit('"s2-20".split("*")')
0.1685205617091654
>>> timeit.timeit('"s2*20".partition("*")')
0.1475598294296372
>>> timeit.timeit('"s2-20".partition("*")')
0.09512975462482132
Solution 2:
In this specific case:
val[val.index('*')+1:]
Find the first occur position of *
, and take a slice from there.
or:
val.split('*', 1)[-1]
The tells to split string only once with delimiter, if you want everything after the first *
.