python在数字后添加字符,如何将数千个分隔符添加到已被转换为Python中的字符串的数字?...

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'

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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值