[Tutor] To get numeric prefix in a string if present
Alan Gauld
alan.gauld at yahoo.co.uk
Tue May 4 04:59:17 EDT 2021
On 04/05/2021 05:03, Manprit Singh 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 ?
Only commenting on the else part - yes, it is correct.
My only comment would be that I prefer to have the break in the first
clause so that it is easier to spot (if you have a lot of code in the
processing section which is not the case here) So I'd write it as:
for ele in st:
if not ele.isdigit():
break
else:
st1 += ele
But that really only matters if the other block is long, in
which case the break can "get lost" in among the other code.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list