关于python:获取一致的密钥错误:

Get consistent Key error:

本问题已经有最佳答案,请猛点这里访问。

尝试运行包含以下代码的脚本以生成文本块时:

1
2
3
4
5
6
7
8
from textwrap import dedent

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

我得到一致的错误KeyError '
"Hello"
。并追溯到.format()的线。

当我删除format时,一切正常,但我需要它动态地输入参数。(最初它位于循环中)


您需要将不是占位符的{}字符加倍:

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

否则,python会看到一个{
"Hello":"world",
}
占位符,其中:之前的部分是占位符名称。

从格式字符串语法文档:

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

(强调我的)。