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

pass multiple argument to sys.stdout.write

是否可以将多个参数传递给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

我该怎么办?

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

>>> 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

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

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