Search code examples
pythonstringstring-formatting

Problem with string formatting when using triple quotes in Python


For this,

name='the name'
address='the address'

s = '''{
  "name": "{0}",
  "address": "{1}"
}
'''
print(s.format(name, address))

I expected it to print the following.

{
  "name": "the name",
  "address": "the address"
}

But I get the following error instead. Why and what is the solution?

KeyError                                  Traceback (most recent call last)
<ipython-input-8-eb4c74e2dd68> in <module>
      8 '''
      9 
---> 10 print(s.format(name, address))

KeyError: '\n  "name"'

Solution

  • The outer {} needs to be escaped for string formatting, you can do so by doubling the { }'s.

    s = '''{{
      "name": "{0}",
      "address": "{1}"
    }}
    '''