如何在Python2中嵌套格式字符串?

时间:2016-03-22 01:13:37

标签: python format

formatter = "%r %r %r %r"
print formatter % (formatter, formatter, formatter, formatter) % ((1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4))


Traceback (most recent call last):
  File "ex8.py", line 2, in <module>
    print formatter % (formatter, formatter, formatter, formatter) % ((1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4))
TypeError: not enough arguments for format string

我的代码有问题吗?或者就是不能这样做。

1 个答案:

答案 0 :(得分:1)

您应该只使用一个元组进行格式化:

formatter = "%r %r %r %r"
print formatter % (formatter, formatter, formatter, formatter) % (1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)

如果你想要更清楚,你可以这样做:

formatter = "%r %r %r %r"
tuples = ((1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4))
print formatter % (formatter, formatter, formatter, formatter) % sum(tuples, ())

或更好:

formatter = "%r %r %r %r"
tuples = (1, 2, 3, 4) * 4
print formatter % ((formatter,) * 4) % tuples