Joan Venge Joan Venge - 5 months ago 8
Python Question

How to format a multi line string with triple quotes inside using Python?

I couldn't find this online but basically I have a string like this:

s = "name={0},
address={1},
nickname={2},
age={3},
comments=
"""
{4}
"""
"


and I need to format this string as is using variables like so:

s.format("alice", "N/A", "alice", 18, "missing person")


I can't change the triple quotes there because the program that will use my string expects that, otherwise won't work.

How can I have this string declared/escaped correctly?

Answer

You could use triple single quotes for the string:

s = '''name={0},
address={1},
nickname={2},
age={3},
comments=
"""
{4}
"""
'''

print s.format("alice", "N/A", "alice", 18, "missing person")

Output:

name=alice,
address=N/A,
nickname=alice,
age=18,
comments=
"""
missing person
"""