[Tutor] Python program to extract numeric suffix from a string

Alan Gauld alan.gauld at yahoo.co.uk
Sun Jul 4 08:43:06 EDT 2021


On 04/07/2021 05:16, Manprit Singh wrote:
> Dear sir,
> 
> Assume a problem to extract a numeric suffix from a string .

You need to define the suffix more precisely. What happens if the name
without suffix, ends in numbers? How do you determine where the name
ends and the suffix starts? Usually we include a separator
(a - or . say) or use a fixed length.

Assuming in this case that the name can not end in a number....

> String is st = "abcd12ghi456"
> The numeric suffix of this string is "456" in case if there is no suffix,
> the program should print " no suffix found"
> The code i have written is given below :
> 
> def return_suffix(st):
>     for x, y in enumerate(reversed(st)):

Please use meaningful names, it makes the code much easier to read.
Even n(dex) and c(har0 would be better than x,y but index,char
would be better still!

>         if not y.isdigit():
>             return st[-x:] if x else "No digit suffix found"


> I feel I have used enumerate and reversed both which makes the program a
> little difficult to read . Can this be written in a more efficient way ?

Ease of reading and efficiency are very different things.
Which is more important to you? Personally I go for ease
of reading unless I know I need speed.

But why use reversed? Why not just iterate in reverse.

Also, it's not good practice to return different data types
depending on the success. It would be better to either
return an invalid suffix(-1 say) or raise an exception.

I've opted to return the suffix as a string and an
empty string if none found.

def f(s):
    if (not s) or s.isdigit(): return s  # empty or no name
    if not s[-1].isdigit(): return ""    # no suffix
    n = -2
    while s[n].isdigit(): n -= 1
    return s[n+1:]

Avoids the enumerate() and reversed() and is arguably readable.
No idea how it performs compared to the original.

-- 
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