String formatting (%)
A. Lloyd Flanagan
alloydflanagan at comcast.net
Thu Apr 29 10:29:25 EDT 2004
pascal.parent at free.fr (Pascal) wrote in message news:<e567c03a.0404280035.79d0d973 at posting.google.com>...
> Hello,
> I've a float number 123456789.01 and, I'de like to format it like this
> "123 456 789.01".
> Is this possible with % character?
No, but this works with integers. Not sure how it compares to the
other approaches mentioned. You could adapt it to do floats by
stopping at the decimal point:
def addCommas(aNumber):
if len(aNumber) < 4: return aNumber
#how many digits before first ,?
prefix = len(aNumber) % 3
#need special case if digits is multiple of 3
if prefix == 0: prefix = 3
result = [aNumber[:prefix]]
for a in range(len(aNumber) / 3):
#get next 'segment' of three digits
segment = aNumber[prefix + 3*a: prefix + 3*a + 3]
if segment: #can be '' if len(aNumber) divisible by 3
result.append(segment)
return ','.join(result)
I'm sure this can be improved.
More information about the Python-list
mailing list