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

标签 python string formatting

为什么我不能使用元组作为新样式格式化程序的参数(“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))

关于python - 以元组为参数的新样式格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15181927/

相关文章:

python - SQLAlchemy 和 SQLite : database is locked

python - 来自谷歌云视觉 API OCR 的逐行数据

python - 当同一行上有多个调用时,如何单步执行 PDB 中的特定可调用函数?

python - 如何格式化函数内的转义序列

java - 什么时候在 Java 中使用 printf 语句?

python - 使用掩码和其他数组替换数组中的值

java - 从字符串中剪切日期

java - 使用 StringBuilder 将字符串的 ArrayList 连接成单个字符串

c - 递归地反转C中的数组

python - 格式化字符串的最 Pythonic 方式