How to write multiple strings in one line?

后端 未结 11 604
谎友^
谎友^ 2020-12-01 03:28

I\'ve started to learn Python with LPTHW and I\'ve gotten to exercise 16:

http://learnpythonthehardway.org/book/ex16.html

And feel like an idiot because I ca

11条回答
  •  有刺的猬
    2020-12-01 03:36

    Here's one way:

    target.write(line1 + '\n' + line2 + '\n' + line3 + '\n')
    

    The reason the following doesn't work

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

    Is that line1 is a variable (note it's not quoted) but '\n' is a string literal (since it's in quotes). The addition operator is overloaded for strings to concatenate (combine) them.

    The reason this doesn't work:

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

    Is because line1 is a variable. When you put it in quotes, it's no longer treated as a variable.

提交回复
热议问题