Welcome, guest | Sign In | My Account | Store | Cart

Some examples:

>>> nprint(9876543210)
'9 876 543 210'
>>> nprint(987654321, period=1, delimiter=",")
'9,8,7,6,5,4,3,2,1,0'
Python, 14 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def nprint(number, period=3, delimiter=" "):
    assert isinstance(number, (int, long)), "only integers are allowed"
    if number >= 0:
        sign = ""
    else:
        sign = "-"
        number = -number
    parts = []
    d = 10 ** period
    while number >= d:
        number, m = divmod(number, d)
        parts.insert(0, "%0*d" % (period, m))
    parts.insert(0, str(number))
    return sign + delimiter.join(parts)

2 comments

Scott Kirkwood 19 years, 8 months ago  # | flag

Problems with negative numbers and floating point values. For example:

>>> nprint(1234.567)
'1.0 234'
>>> nprint(-1234)
'-1234'
Dmitry Vasiliev (author) 19 years, 8 months ago  # | flag

Thanks! But there is no correct way for printing floating point values so now only integers are allowed.

Created by Dmitry Vasiliev on Thu, 26 Aug 2004 (PSF)
Python recipes (4591)
Dmitry Vasiliev's recipes (9)

Required Modules

  • (none specified)

Other Information and Tasks