[Tutor] Closing triple quotation marks.
Steven D'Aprano
steve at pearwood.info
Sat Jun 18 16:23:30 CEST 2011
Lisi wrote:
> But I still can't write to the file.
>
> If I do:
> target.write(line1)
>
> The value of the variable line1 is written to the file. But if I put the
> three variables into the write command, what gets printed is the name of the
> variables, not their values. I am clearly still doing something wrong. But I
> can't see what. I have even tried to see whether ''' gave a different result
> from """, but it doesn't. I have accepted KWrite's idea of what the white
> space should be, and I have adapted it to all the variations I can think of.
What gets written is the string that is passed to write(). Anything
inside quotation marks (single, or triple) is a string, not a variable.
"line1" has nothing to do with the variable line1, it is merely the
letters l i n e followed by digit 1. Python will never try to guess
whether you mean a string "x" or a variable x. If it is inside quote
marks, it is always a string.
There are a number of ways to write the contents of variables to a file.
The best way depends on how many variables you have, and whether they
are already strings or not. Here are a few:
# line1 etc. are already strings, and there are only a few of them:
target.write(line1 + '\n') # add a newline after each string
target.write(line2 + '\n')
target.write(line3 + '\n')
# here's another way, using String Interpolation:
template = """
%s
%s
%s
"""
text = template % (line1, line2, line3)
# each %s inside the template is replaced with the contents
# of line1, line2 and line3 respectively
target.write(text)
# finally, if you have many lines, or a variable number of them:
lines = [line1, line2, line3] # and possible more...
text = '\n'.join(lines)
target.write(text)
--
Steven
More information about the Tutor
mailing list