Search code examples
pythonkeyerror

Get consistent Key error: \n


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)


Solution

  • 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).