开发者

Learning Python the Hard Way: Ex16 Extra Credit

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 wo开发者_运维问答rk, 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!


How about this?

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


The % interpolation operator applies to strings. You're applying it to the return value of target.write, which doesn't return anything (hence NoneType). You want to do the interpolation on the string itself:

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

Most people learning Python first encounter % in the context of the print statement, so it's understandable to think it's closely connected with output, but it does all its work at the string level.


Your original attempts were attempting to use the % operator with the return value of target.write() -- which is None. You need to have % happen inside the () for target.write:

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

Note that another solution is:

target.write('\n'.join([line1, line2, line3, '']))

Edit

Added empty string at end to force a third newline (otherwise there would be only two).


Another method which worked for me in Python 3 is:

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


I myself used this script to write lines in the file for the same question. (using python 3.6)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜