Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning Python the Hard Way: Ex16 Extra Credit

Tags:

python

I'm stumped when it comes to the 3rd question on the extra credit. The code in question is this:

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

The question asks you to "use strings, formats, and escapes to print out line1, line2, and line3 with just one target.write() command instead of 6.

So, I thought I'd write it like this:

target.write("%s + \n + %s + \n + %s + \n") % (line1, line2, line3)

And it returned: TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple.' I did some research on them and couldn't really find anything, but it returned the same error using %r.

Thinking the + signs were incorrect since it was all a single string, I deleted them for:

target.write("%s \n %s \n %s \n") % (line1, line2, line3)

Still nothing. Then I tried:

target.write("%s" + "\n" + "%s" + "\n" + "%s" + "\n") % (line1, line2, line3)

This one at least changed the error to: TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'. The same error was produced for this variation:

target.write("%s") % (line1 + line2 + line3)

Anyway, it's pretty obvious I'm stuck somewhere. I'm thinking my problem is centered around the %s/%r I'm using, but I can't find an alternative that I think would work, or maybe I'm just writing the write statement incorrectly.

Sorry if this drug on, I just thought I'd try to explain my thought process. Thanks for the assistance!

like image 726
Dan Avatar asked Sep 19 '11 20:09

Dan


Video Answer


1 Answers

How about this?

target.write("%s\n%s\n%s\n" % (line1, line2, line3))
like image 108
rumpel Avatar answered Oct 20 '22 23:10

rumpel