Mr.Slow
Mr.Slow

Reputation: 560

How to remove all digits after the last string

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

Upvotes: 1

Views: 83

Answers (2)

Kelly Bundy
Kelly Bundy

Reputation: 27588

You could use rstrip:

text.rstrip(' 0123456789')

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

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.

Upvotes: 1

Related Questions