[Tutor] To get numeric prefix in a string if present
Manprit Singh
manpritsinghece at gmail.com
Tue May 4 03:30:06 EDT 2021
Dear Sir ,
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 .
On Tue, May 4, 2021 at 9:33 AM Manprit Singh <manpritsinghece at gmail.com>
wrote:
> Dear sir ,
> Consider the problem of getting numeric prefix in a string if present.
>
> st = "23fgh"
> st1 = ""
> for ele in st:
> if ele.isdigit():
> st1 += ele
> else:
> break
> print(st1 or "Numeric prefix not in string" )
>
> Here st variable contains the string from which the numeric prefix has to
> be retrieved, which is 23 . The code written above gives the right answer.
>
> My major question is - The way I have used break statement with else is
> correct ?
> iIam using an empty string st1 and then concatenating the digit characters
> with it, this doesn't feel pythonic. need to know any better way to solve
> this .
> Kindly guide
>
> Regards
> Manprit Singh
>
>
More information about the Tutor
mailing list