Home > Back-end >  How to remove all digits after the last string
How to remove all digits after the last string

Time:01-31

I would like to remove all the digits from the end of: "Car 7 5 8 7 4". How can I achieve it using regex or other approaches? I tried following but it only deletes 1 digit:

re.sub(r'\s*\d $', '', text)

Thanks

CodePudding user response:

You could use rstrip:

text.rstrip(' 0123456789')

CodePudding user response:

You can use

re.sub(r'\s*\d[\d\s]*$', '', text)

See the regex demo.

Details:

  • \s* - zero or more whitespaces
  • \d - a digit
  • [\d\s]* - zero or more digits/whitespaces
  • $ - end of string.
  • Related