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
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.
The author suggested using the formats, the strings and the escapes, so the following works. This implements Python's f-strings:
target.write(f"{line1} \n{line2} \n{line3} \n")
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) )
This info was really helpful. I got the right results by doing the following:
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
The idea of concatenating would never have occurred to me.
below line works for me,
target.write(line1 + line + line2 + line + line3 + line)
Before that i added
line = '\n'
my code like:
from sys import argv
script, filename = argv
print 'Appending process starts on: %r' % filename
target = open(filename, 'a')
print 'Enter the contents:\t'
line1 = raw_input('Next:\t')
line2 = raw_input('Next:\t')
line3 = raw_input('Next:\t')
line = '\n'
target.write(line1 + line + line2 + line + line3 + line)
print 'Thank you !'
This worked for me.
target.write("line1\nline2\nline3\n")
Also, the keyword which made it clicked for me was mentioned by Ewart, "'\n' only make sense inside a string literal."