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

Manprit Singh manpritsinghece at gmail.com
Sun Jul 4 00:16:32 EDT 2021


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