python - 以元组为参数的新样式格式

为什么我不能使用元组作为新样式格式化程序的参数(“string”.format())?它在旧样式中工作正常(“字符串”%)?

此代码有效:

>>> tuple = (500000, 500, 5)
... print "First item: %d, second item: %d and third item: %d." % tuple

    First item: 500000, second item: 500 and third item: 5.

这不是:

>>> tuple = (500000, 500, 5)
... print("First item: {:d}, second item: {:d} and third item: {:d}."
...       .format(tuple))

    Traceback (most recent call last):
     File "<stdin>", line 2, in <module>
    ValueError: Unknown format code 'd' for object of type 'str'

即使使用 {!r}

>>> tuple = (500000, 500, 5)
... print("First item: {!r}, second item: {!r} and third item: {!r}."
...       .format(tuple))

    Traceback (most recent call last):
     File "<stdin>", line 2, in <module>
    IndexError: tuple index out of range

虽然它以这种方式工作:

>>> print("First item: {!r}, second item: {!r} and third item: {!r}."
...       .format(500000, 500, 50))

    First item: 500000, second item: 500 and third item: 5.

最佳答案

旧的格式化方式使用二元运算符,%。就其性质而言,它只能接受两个参数。新的格式化方式使用一种方法。方法可以接受任意数量的参数。

由于您有时需要将多个内容传递给格式化,并且始终使用一个项目创建元组有点笨拙,因此旧式方法提出了一个技巧:如果您将其作为元组传递,它将使用元组的内容作为要格式化的东西。如果你传递给它的不是元组,它会使用它作为唯一的格式。

新方法不需要这样的技巧:因为它是一种方法,它可以接受任意数量的参数。因此,需要将多个要格式化的东西作为单独的参数传递。幸运的是,您可以使用 * 将元组解包为参数:

print("First item: {:d}, second item: {:d} and third item: {:d}.".format(*tuple))

https://stackoverflow.com/questions/15181927/

相关文章:

javascript - 如何设置 VSCode 以将花括号放在新行上?

java - 日期和时间格式取决于区域设置

html - 在 Visual Studio Code 中格式化 html 代码,使属性位于不同的行

xml - 如何在 sublime 3 中安装 sublime text indent xml

Java - 将双值格式化为美元金额

java - 使用 Java 将电话号码转换为国际格式 (E.164) 的最佳方法是什么?

c - intptr_t 和 uintptr_t 的字符串格式

java - 如何使用 Java 的 DecimalFormat 进行 "smart"货币格式?

asp.net - 如何在 ASP.NET RadioButtonList 中的项目之间添加空格

formatting - excel中的数字格式: Showing % value without