如何将数千个分隔符添加到已被转换为Python中的字符串的数字? [英] how to add thousands separator to a number that has been converted to a string in python?
问题描述
在我的场景(python 2.7)中,我有:
str(var)
其中,var是一个变量,有时需要数千个分隔符,例如1,500,但正如您所看到的,已经转换为字符串(用于并置)。
我希望能够将这个变量作为一个带有数千个分隔符的字符串打印出来。
我已经阅读过将格式添加到数字的解决方案,例如:
>>>格式(f)
'18,446,744,073,709,551,616.00'
从 https://stackoverflow.com/a/1823189/1063287
但是这似乎只适用于一个数字,不适用于已经转换为字符串的数字。
谢谢。
edit:对于更具体的上下文,这里是我的实现场景:
print'the cost = $'+ str(var1)+'\\\
'
print'the cost = $'+ str(var2)+'\\\
'
我有几个'vars'。
str(var)
和concatenation,即什么 .format()
是 for 。根据 var 的类型,选择以下其中一个:
'{: ,格式化(var)#格式化整数
'{:,。2f}'。format(var)#格式化小数或浮点数
$ p
$ b 取决于您拥有的号码类型。
pre $ >> ;> var = 12345678.123
>>> '{:,}'。format(int(var))#忽略`.123`部分
'12,345,678'
>>> '{:,。2f}'。format(var)
'12,345,678.12'
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'
这篇关于如何将数千个分隔符添加到已被转换为Python中的字符串的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!