如何使用返回多个值作为格式字符串输入的函数,而不会出现TypeError: not enough arguments for format string
错误?
>>> def foo():
... return 1, 2
...
>>> foo()
(1, 2)
>>> print "%d,%d,%d" % foo(), 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
预期输出:“ 1,2,3”
python大神给出的解决方案
元素索引
string.format()
功能更强大,可让您access list elements or even attributes:
>>> print "{0[0]},{0[1]},{1}".format(foo(), 3)
1,2,3
串联元组
foo(), 3
的问题在于它是一个元组和一个整数,这是两种不同的类型。相反,您可以通过串联创建3元组。如果使用string.format()
则比较棘手,因为您首先需要使用*
运算符将其解压缩,以便可以将其用作参数:
>>> foo() + (3,)
(1, 2, 3)
>>> print "%d,%d,%d" % (foo() + (3,))
1,2,3
>>> print "{},{},{}".format(*foo() + (3,))
1,2,3
临时变量
当然,您总是可以这样操作,这很明显但是很冗长:
>>> foo1, foo2 = foo()
>>> print "%d,%d,%d" % (foo1, foo2, 3)
1,2,3