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

Roel Schroeven roel at roelschroeven.net
Sun Jul 4 07:07:59 EDT 2021


Alternative:

def ret_suffix(st):
     without_number_suffix = st.rstrip('0123456789')
     if without_number_suffix == st:
         return "No digit suffix found"
     return st[len(without_number_suffix):]


Manprit Singh schreef op 4/07/2021 om 6:16:
> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

-- 
"'How to Stop Worrying and Learn to Love the Internet':
1) everything that’s already in the world when you’re born is just
     normal;
2) anything that gets invented between then and before you turn
    thirty is incredibly exciting and creative and with any luck you can
    make a career out of it;
3) anything that gets invented after you’re thirty is against the
    natural order of things and the beginning of the end of civilisation
    as we know it until it’s been around for about ten years when it
    gradually turns out to be alright really.
Apply this list to movies, rock music, word processors and mobile
phones to work out how old you are."
         -- Douglas Adams



More information about the Tutor mailing list