Ex16 Drill 3 Question

Hey,
Currently reading “Learn Python 3 The Hard Way”.
I am on ex16 and the 3rd study drill says:
image

I am not sure if target.write() can print out, but from what I see it only accepts one argument,
so I am guessing I need to pass it a variable as a parameter.

The way I made this work was like this:

bundle = line1 + "\n" + line2 + "\n" + line3 + "\n"
# writes the strings in the 3 vars to the opened file
target.write(bundle)

However I don’t think that’s the intended solution since this has nothing to do
with formats. However when I tried to pass a print function to target.write
it didn’t work so I couldn’t figure out a different way to do it.

Can you give me some hints on how the author originally intended for this to be solved?
thanks.

You could do

target.write(f"{line1}\n{line2}\n{line3}")

if you insist on using string formatting.

But I think your solution is fine and it can easily be changed to deal with the general case where you need to write an arbitrary number of lines to the file:

# let lines be a list of lines
bundle = "\n".join(lines)
target.write(bundle)

But if .write only accepts one argument, then how does it accept all these vars? Is the whole formatted string considered one argument?

Yes.

(“Post must be at least 20 characters” and quotes don’t count! Really?!)

1 Like
A free service run by Zed A. Shaw for learncodethehardway.org.