Cleb Cleb - 10 months ago 45
Python Question

How to remove everything after the last number in a string

I have strings like this:

w = 'w123 o456 t789-- --'

My goal is to remove everything after the last number, so my desired output would be

w123 o456 t789

It is not always the same ending, so
-- --
is just one example.

import re

re.sub('(.*?)(\d)', '', w)

gives me

'-- --'

How can I modify the command so that it removes this part?


You can use:

>>> w = 'w123 o456 t789-- --'
>>> re.sub(r'\D+$', '', w)
'w123 o456 t789'

\D+$ will remove 1 or more non-digit characters before end anchor $.