Formatting question : printing numbers with thousands separators ?
Skip Montanaro
skip at pobox.com
Fri Aug 31 09:11:57 EDT 2001
Fred> how do I print 246814345 as 246,814,345 (or 246 814 345) ?
I'm sure there are more clever ways, but this seems to work:
def separate(n, sep=','):
ln = list(str(n))
ln.reverse()
newn = []
while len(ln) > 3:
newn.extend(ln[:3])
newn.append(sep)
ln = ln[3:]
newn.extend(ln)
newn.reverse()
return "".join(newn)
>>> separate("2342342342344567")
'2,342,342,342,344,567'
>>> separate("2342342342344567", sep=' ')
'2 342 342 342 344 567'
>>> separate(5)
'5'
>>> separate(35)
'35'
>>> separate(235)
'235'
>>> separate(1235)
'1,235'
>>> separate(1235, ' ')
'1 235'
--
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/
More information about the Python-list
mailing list