I used Learnpythonthehardway.org, and in exercise 16 the study drills say the following: "Use strings, formats, and escapes o print out line 1, line2, and line3 with just one target.write() command instead of six."
And so, I changed:
target.write(line1, "\n", line2, "\n" line3, "\n")
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
Into:
target.write("%s \n %s \n %s \n") %(line1, line2, line3)
Can anyone explain what I did wrong?
file.write() takes only one argument, not more. Only the print() function handles more than one argument for you.
You need to format your string to one argument instead of trying to 'format' the return value of the target.write() function:
target.write("%s\n%s\n%s\n" % (line1, line2, line3))
or use the print() function to add the newlines and the separators:
print(line1, line2, line3, sep='\n', file=target)
print() as function is the default in Python 3; if you are using Python 2 you can turn print the statement into print() the function by adding:
from __future__ import print_function
at the start of your module.
Note that the original excercise code writes the lines to the file without spaces in between.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With