I have the following code:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
Here target is the file object and line1, line2, line3 are the user inputs. I want to use only a single target.write() command to write this script. I have tried using the following:
target.write("%s \n %s \n %s \n") % (line1, line2, line3)
But doesn't that put a string inside another string but if I use the following:
target.write(%s "\n" %s "\n" %s "\n") % (line1, line2, line3)
The Python interpreter(I'm using Microsoft Powershell) says invalid syntax. How would I able to do it?
You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string.
You can use write function to write multiple lines by separating lines by '\n'.
You're confusing the braces. Do it like this:
target.write("%s \n %s \n %s \n" % (line1, line2, line3))
Or even better, use writelines
:
target.writelines([line1, line2, line3])
another way which, at least to me, seems more intuitive:
target.write('''line 1
line 2
line 3''')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With