user3270211
user3270211

Reputation: 933

Python Triple-quoted strings with variable

Trying to write to a file with variables, but that is returning error:

template = """1st header line
second header line
There are people in rooms
and the %s
"""
with  open('test','w') as myfile:
    myfile.write(template.format()) % (variable)

Upvotes: 1

Views: 6013

Answers (3)

Bhargav Rao
Bhargav Rao

Reputation: 52071

The Error

myfile.write(template.format()) returns nothing to which you are using % operator to concatenate

Minimal Edit

You can perfectly use %s .The problem is you mismatched parenthesis and the parenthesis i.e. ) should be after your variable as in myfile.write(template.format() % (variable)). But as template.format() is redundant, it can be ignored. Thus the correct way is

myfile.write(template % (variable))

Note:- Any string with an empty format() and no {} in the string returns the string itself

Upvotes: 1

falsetru
falsetru

Reputation: 368914

The given string literal is printf-style string. Use str % arg:

with  open('test', 'w') as myfile:
    myfile.write(template % variable)

To use str.format, you should use placeholder {} or {0} instead of %s.

Upvotes: 1

grayshirt
grayshirt

Reputation: 643

The .format method expects you to template the blanks to be filled in your string with the {}-style, not %s. It also expects the interpolated values to be given as its arguments.

template = """1st header line
second header line
There are people in rooms
and the {}
"""

myfile.write(template.format(variable))

Upvotes: 2

Related Questions