4

在 Python 中,如何一次执行多种格式:

所以我想让一个数字没有小数位并且有一个千位分隔符:

数量 = 80000.00

我希望它是 80,000

我知道我可以单独做这两件事,但我将如何将它们结合起来:

"{:,}".format(num) # this will give me the thousands separator
"{0:.0f}".format(num) # this will give me only two decimal places

那么可以将这些结合在一起吗?

4

1 回答 1

11

您可以组合这两个格式字符串。逗号在冒号之后:

>>> "{:,.0f}".format(80000.0)
'80,000'

请注意,当仅格式化单个值时,您也可以使用 freeformat()函数而不是方法:str.format()

>>> format(80000.0, ",.0f")
'80,000'

编辑,在 Python 2.7 中引入了包含千位分隔符,因此上述转换在 Python 2.6 中不起作用。在该版本中,您将需要滚动自己的字符串格式。一些临时代码:

def format_with_commas(x):
    s = format(x, ".0f")
    j = len(s) % 3
    if j:
         groups = [s[:j]]
    else:
         groups = []
    groups.extend(s[i:i + 3] for i in range(j, len(s), 3))
    return ",".join(groups)
于 2012-08-01T16:23:04.583 回答