String formatting (%)

Peter Hansen peter at engcorp.com
Thu Apr 29 10:50:51 EDT 2004


Peter Hansen wrote:

>  >>> import re
>  >>> s = '21421906.12'
>  >>>
>  >>> re.sub(r'(?<=\d)(?=(\d\d\d)+\.)', ',', s)
> '21,421,906.12'
> 
>>     Of course, the OP would substitute spaces for the commas.
> 
>  >>> _.replace(',', ' ')
> '21 421 906.12'

And in case the OP is entirely unfamiliar with regular
expressions, you wouldn't actually do a separate "replace"
operation like the above, so

   re.sub(r'(?<=\d)(?=(\d\d\d)+\.)', ' ', s)

should work nicely, at least with any floating that *always*
has a decimal point present.  If the numbers might sometimes
not have a decimal point, I think this will do the job, so
it's a more general solution:

   re.sub(r'(?<=\d)(?=(\d\d\d)+(\.|$))', ' ', s)

Note that addition of an alternate for \. at the end of the pattern.

-Peter



More information about the Python-list mailing list