Search code examples
pythonlogic

Python: remove last number of a string


I need 4 lines of code to do this script but I think it's possible to do it in 2 (maybe even 1 ! let's dream). Do someone has a solution ? You can test the code to see the expected result.

def remove_nbr_at_the_end_of_the_string(my_str):
    while my_str[-1] in ["0", "1", "2", "3" ,"4" ,"5" ,"6" ,"7" ,"8" ,"9"]:
        my_str = my_str[:-1]
    if my_str[-1] == " ": my_str = my_str[:-1]
    return my_str


for text in ["ACCDS 122", "GR DDF 0332", "MLMD 12 334", "MMED DFE"]:
    print(remove_nbr_at_the_end_of_the_string(text))

Solution

  • Use this to remove last number as well as space from the end.

    my_str.rstrip('0123456789').strip()