[Tutor] To get numeric prefix in a string if present

Manprit Singh manpritsinghece at gmail.com
Tue May 4 00:03:29 EDT 2021


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