8

When trying to run a script containing the following code for generating text block:

from textwrap import dedent

text = dedent("""\
   yada yada '1' ('2','3',4') 
   ('{0}', Null, '{1}',
   '{
      "Hello":"world",
    }', '1', '{2}');""").format("yada1","yada2","yada3")

I get consistent error KeyError '\n "Hello"
and trace back pointing at the line of the .format().

When I remove the format everything is ok, but I need it to enter parameters dynamically.
(Originally its reside inside a loop)

0

1 Answer 1

17

You need to double the { and } characters that are not placeholders:

text = dedent("""\
   yada yada '1' ('2','3',4') 
   ('{0}', Null, '{1}',
   '{{
      "Hello":"world",
    }}', '1', '{2}');""").format("yada1","yada2","yada3")

otherwise Python sees a {\n "Hello":"world",\n} placeholder, where the part up to the : is the placeholder name.

From the Format String Syntax documenattion:

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

(emphasis mine).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.