Get consistent Key error: \n [duplicate]

亡梦爱人 提交于 2020-06-14 07:05:39

问题


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)


回答1:


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



来源:https://stackoverflow.com/questions/32224197/get-consistent-key-error-n

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!