Cleb Cleb - 1 year ago 118
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?

Answer Source

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 $.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download