python - How to remove everything (except certain characters) after the last number in a string -
this follow-up of this question.
there learned how remove characters after last number in string; can turn
w = 'w123 o456 t789-- --'
into
w123 o456 t789
now might have strings this:
w = 'w123 o456 (t789)'
in case,
re.sub(r'\d+$', '', w)
would give me
w123 o456 (t789
so have 2 closely related questions:
1) how can modify command re.sub(r'\d+$', '', w)
in way characters kept (e.g. parenthesis)?
2) how can modify command re.sub(r'\d+$', '', w)
characters removed (e.g. dashes , white spaces)?
edit
@martin bonner's answer gets close e.g.
w='w123 -o456 t789--) --'
the command
re.sub('[- ]+$', '', w)
gives me w123 -o456 t789--)
should rid of remaining dashes.
you may use re.sub in callback replacement pattern.
re.sub(r'\d+$', lambda m: re.sub(r'[^()]+','',m.group(0)), s)
here, match symbols other digits @ end of string, pass value callback, , symbols other (
, )
removed value.
Comments
Post a Comment