Most pythonic way to format a number with commas?
Ned Batchelder
ned at nedbatchelder.com
Thu Jul 11 20:26:18 EDT 2002
For dir/ls replacement script, I wanted to format file sizes with
commas as a thousands separator. I didn't find anything in the
standard library, but figured it couldn't be too hard to do with list
manipulation. I came up with this:
def formatNumber(num):
"""Format a number for display"""
sl = [c for c in str(num)]
for i in range(len(sl)-3, 0, -3):
sl[i:i] = [',']
return string.join(sl, '')
While this works, and uses list ops to do it, I thought it would be
possible to get a simpler solution.
Is there one?
--Ned.
http://www.nedbatchelder.com
More information about the Python-list
mailing list