Question

I have a multiline string, where I want to change certain parts of it with my own variables. I don't really like piecing together the same text using + operator. Is there a better alternative to this?

For example (internal quotes are necessary):

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

I want to be able to use this multiple times to form a larger string, which 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)
Was it helpful?

Solution

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 star operator will unpack the list into the format method.

OTHER TIPS

In addition to a list, you can also use a dictionary. This is useful if you have many variables to keep track of at once.

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)

Note, I typed the text differently because it lets me line up the text easier. You have to add a '\' at the beginning """ and before the end """ though.

Now if you have several dictionaries in a list you can easily do

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)

or using list comprehensions

alltext = [text.format(**person) for person in people]
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".
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top