in my scenario (python 2.7), i have:
str(var)
where var is a variable that sometimes requires thousands separators eg 1,500 but as you can see has been converted to a string (for concatenation purposes).
i would like to be able to print out that variable as a string with thousands separators.
i have read solutions for adding formatting to a number eg:
>>> '{:20,.2}'.format(f)
'18,446,744,073,709,551,616.00'
from https://stackoverflow.com/a/1823189/1063287
but this seems to be applicable just for a number, not for a number that has been converted to a string.
thank you.
edit: for more specific context, here is my implementation scenario:
print 'the cost = $' + str(var1) + '\n'
print 'the cost = $' + str(var2) + '\n'
and i have several 'vars'.
Do not use str(var)
and concatenation, that is what .format()
is for. Depending on the type of var
pick one of:
'{:,}'.format(var) # format an integer
'{:,.2f}'.format(var) # format a decimal or float
depending on the type of number you have.
>>> var = 12345678.123
>>> '{:,}'.format(int(var)) # ignore the `.123` part
'12,345,678'
>>> '{:,.2f}'.format(var)
'12,345,678.12'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With