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

Manprit Singh manpritsinghece at gmail.com
Sun Jul 4 02:17:04 EDT 2021


Dear sir,

Correcting the function written for the problem :
Problem to extract a numeric suffix from a string

def ret(st):
    for x, y in enumerate(reversed(st)):
        if not y.isdigit():
            return st[-x:] if x else "No digit suffix found"
    return st

Anything more readable in comparison to this function be done ? Kindly
guide

Regards
Manprit Singh




On Sun, Jul 4, 2021 at 9:46 AM Manprit Singh <manpritsinghece at gmail.com>
wrote:

> Dear sir,
>
> Assume a problem to extract a numeric suffix from a string .
> 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)):
>         if not y.isdigit():
>             return st[-x:] if x else "No digit suffix found"
>
> st1 = "abcd1gh123"
> ans = return_suffix(st1)
> print(ans)  # gives the right answer as '123'
>
> st1 = "abcd1gh"
> ans = return_suffix(st1)
> print(ans)   # gives the right answer  as  '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 ?
>
> Need your guidance.
>
> Regards
> Manprit Singh
>


More information about the Tutor mailing list