将多个参数传递给sys.stdout.write

时间:2015-08-03 08:18:02

标签: python python-3.x stdout

是否可以将多个参数传递给sys.stdout.write?我看到的所有例子都使用了一个参数。

以下陈述不正确。

sys.stdout.write("\r%d of %d" % read num_lines)
Syntax Error: sys.stdout.write

sys.stdout.write("\r%d of %d" % read, num_lines)
not enough arguments for format string

sys.stdout.write("\r%d of %d" % read, %num_lines)
Syntax Error: sys.stdout.write

sys.stdout.write("\r%d of %d" % read, num_lines)
not enough arguments for format string

我该怎么办?

1 个答案:

答案 0 :(得分:5)

您需要将变量放在元组中:

>>> read=1
>>> num_lines=5
>>> sys.stdout.write("\r%d of %d" % (read,num_lines))
1 of 5>>> 

或使用str.format()方法:

>>> sys.stdout.write("\r{} of {}".format(read,num_lines))
1 of 5

如果您的参数在iterable中,您可以使用解包操作将它们传递给字符串的format()属性。

In [18]: vars = [1, 2, 3]
In [19]: sys.stdout.write("{}-{}-{}".format(*vars))
1-2-3
相关问题