[Tutor] To get numeric prefix in a string if present
Peter Otten
__peter__ at web.de
Tue May 4 04:05:59 EDT 2021
On 04/05/2021 09:30, Manprit Singh wrote:
> st = "23fgh"
> st[:st.index(st.lstrip("0123456789"))]
> what about this ? This works well too for the said operation of getting the
> numeric prefix of a string .
What if the string contains only digits?
>>> def numerical_prefix(s):
return s[:s.index(s.lstrip("0123456789"))]
>>> numerical_prefix("abc")
''
>>> numerical_prefix("321abc")
'321'
>>> numerical_prefix("321") # wrong
''
Instead of using str.index() you could calculate the prefix length:
>>> def numerical_prefix(s):
return s[:len(s) - len(s.lstrip("0123456789"))]
>>> numerical_prefix("abc")
''
>>> numerical_prefix("321abc")
'321'
>>> numerical_prefix("321")
'321'
More information about the Tutor
mailing list