How to write multiple strings in one line?
target.write(line1 \n, line2 \n, line3 \n)
'\n' only make sense inside a string literal. Without the quotes, you don't have string literals.
target.write('line1 \n, line2 \n, line3 \n')
Ok, now everything is a string literal. But you want line1, line2, line3 to not be string literals. You need those as python expressions to refer the variables in question. Basically, you have to put quotes around strings that are actually text like "\n" but not around variables. If you did that, you might have gotten something like:
target.write(line1 '\n' line2 '\n' line3 '\n')
What is 2 2
? It's nothing. You have to specify to python how to combine the two pieces. So you can have 2 + 2
or 2 * 2
but 2 2
doesn't make any sense. In this case, we use add to combine two strings
target.write(line + '\n' + line2 + '\n' + line3 + '\n')
Moving on,
target.write(%r \n, %r \n, %r \n) % (line1, line2, line3)
Again \n
only makes sense inside a string literal. The % operator when used to produce strings takes a string as its left side. So you need all of that formatting detail inside a string.
target.write('%r \n', '%r \n', '%r \n') % (line1, line2, line3)
But that produce 3 string literals, you only want one. If you did this, write complained because it excepts one string, not 3. So you might have tried something like:
target.write('%r \n%r \n%r \n') % (line1, line2, line3)
But you want to write the line1, line2, line3 to the file. In this case, you are trying to the formatting after the write has already finished. When python executes this it will run the target.write first leaving:
None % (line1, line2, line3)
Which will do nothing useful. To fix that we need to to put the % ()
inside the .write()
target.write('%r\n%r\n%r\n' % (line1, line2, line3))
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.
Your last try looks promising. It should look like:
"%s \n %s \n %s" % (line1, line2, line3)
this applies the operator %
to a string (with 3 %s
placeholders) and a tuple of values to substitute (here, strings). The result is the formatted string.
So you'd need to wrap that in the function which takes the result:
target.write("%s \n %s \n %s" % (line1, line2, line3) )