3 number and dot..

George Sakkis george.sakkis at gmail.com
Wed Oct 31 21:16:23 EDT 2007


On Oct 31, 7:32 pm, bearophileH... at lycos.com wrote:
> Hrvoje Niksic:
>
> > I'm surprised that no one has proposed a regex solution, such as:
>
> I presume many Python programmers aren't much used in using REs.
>
> > >>> import re
> > >>> re.sub(r'\d{1,3}(?=(?:\d{3})+$)', r'\g<0>.', str(1234567))
> > '1.234.567'
>
> It works with negative numbers too. It's a very nice solution of a
> simple problem that shows what you can do with REs. But I think that
> RE has to be expanded & splitted (and maybe even commented) with a
> VERBOSE, to improve readability, maybe somethign like:
>
> \d {1,3}
> (?=                # lockahead assertion
>   (?: \d {3} )+ $  # non-group
> )
>
> Bye,
> bearophile


That's 3 times faster on my box and works for negatives too:

def localize(num, sep='.'):
    d,m = divmod(abs(num),1000)
    return '-'*(num<0) + (localize(d)+sep+'%03d'%m if d else str(m))


George




More information about the Python-list mailing list