[Tutor] removing padded numbers
Kent Johnson
kent37 at tds.net
Thu Jan 11 03:43:28 CET 2007
Christopher Spears wrote:
> Does anyone how to remove padded numbers with python?
> I want to be able to take a file like
>
> afile.0001.cin
>
> and convert it to
>
> afile.1.cin
The straightforward way is just to pick it apart and put it back
together the way you want it:
>>> a, b, c = 'afile.0001.cin'.split('.')
>>> '%s.%s.%s' % (a, b.lstrip('0'), c)
'afile.1.cin'
Or if you prefer, here is an obscure one-liner using the ability of
re.sub() to take a callable as the replacement argument. (That is a
pretty cool feature but overkill here...) This one replaces any run of
digits with the same digits with leading zeros removed:
>>> import re
>>> re.sub(r'\d+', lambda m: m.group().lstrip('0'), 'afile.0001.cin')
'afile.1.cin'
Kent
More information about the Tutor
mailing list