The most elegant way to format multi-line strings in Python

I have a line with several lines where I want to change some parts of it with my own variables. I don’t really like to collect the same text using the + operator. is there a better alternative to this?

For example (internal quotation marks are required):

line = """Hi my name is "{0}".
I am from "{1}".
You must be "{2}"."""

I want to be able to use this several times to form a large string that will look like this:

Hi my name is "Joan".
I am from "USA".
You must be "Victor".

Hi my name is "Victor".
I am from "Russia".
You must be "Joan".

Is there a way to do something like:

txt == ""
for ...:
    txt += line.format(name, country, otherName)
+3
source share
3 answers
info = [['ian','NYC','dan'],['dan','NYC','ian']]
>>> for each in info:
    line.format(*each)


'Hi my name is "ian".\nI am from "NYC".\nYou must be "dan".'
'Hi my name is "dan".\nI am from "NYC".\nYou must be "ian".'

The stellar operator will unpack the list into a method format.

+4
source

. , .

text = """\
Hi my name is "{person_name}"
I am from "{location}"
You must be "{person_met}"\
"""
person = {'person_name': 'Joan', 'location': 'USA', 'person_met': 'Victor'}

print text.format(**person)

, -, . '\' "" "" " .

, ,

people = [{'person_name': 'Joan', 'location': 'USA', 'person_met': 'Victor'},
          {'person_name': 'Victor', 'location': 'Russia', 'person_met': 'Joan'}]

alltext = ""
for person in people:
  alltext += text.format(**person)

alltext = [text.format(**person) for person in people]
+2
line = """Hi my name is "{0}".
I am from "{1}".
You must be "{2}"."""

tus = (("Joan","USA","Victor"),
       ("Victor","Russia","Joan"))

lf = line.format # <=== wit, direct access to the right method

print '\n\n'.join(lf(*tu) for tu in tus)

result

Hi my name is "Joan".
I am from "USA".
You must be "Victor".

Hi my name is "Victor".
I am from "Russia".
You must be "Joan".
+1
source

All Articles