Pass multiple arguments to sys.stdout.write
Can multiple arguments be passed to sys.stdout.write
? All the examples I've seen use one parameter.
The following statements are incorrect.
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
What should I do?
+3
source to share
1 answer
You need to put variables in a tuple:
>>> read=1
>>> num_lines=5
>>> sys.stdout.write("\r%d of %d" % (read,num_lines))
1 of 5>>>
Or use the method str.format()
:
>>> sys.stdout.write("\r{} of {}".format(read,num_lines))
1 of 5
If your arguments are inside an iteration, you can use an unboxing operation to pass them to the string attribute format()
.
In [18]: vars = [1, 2, 3]
In [19]: sys.stdout.write("{}-{}-{}".format(*vars))
1-2-3
+5
source to share