help formatting number

Christian Tanzer tanzer at swing.co.at
Wed Jun 14 02:10:00 EDT 2000


"Mario" <mtbros at tin.it> wrote :

> I have an integer variable and I want it to become a string variable
> formatted so that there is a dot between each three digits of the original
> number. An example:
> var =3456789
> It must become:
> "3.456.789"
> Ideas ?

-------------------------------------------------------------------------------
Python 1.5.2 (#5, Jan  4 2000, 11:37:02)  [GCC 2.7.2.1] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import re
>>> var =3456789
>>> sep_1000 = "."
>>> sep_1000_pat = re.compile ("(\d{1,3}) (?= (?: \d\d\d)+ (?! \d) )", re.X)
>>> print sep_1000_pat.sub ( r"\g<1>%s" % sep_1000, "%s" % var)
3.456.789
>>> 
-------------------------------------------------------------------------------

PS: If you want to understand the regular expression, don't ask me,
    get Jeffrey Friedl's book `Mastering Regular Expressions'

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92





More information about the Python-list mailing list