Get consistent Key error: \n
Get consistent Key error: \n
当尝试 运行 一个包含以下用于生成文本块的代码的脚本时:
from textwrap import dedent
text = dedent("""\
yada yada '1' ('2','3',4')
('{0}', Null, '{1}',
'{
"Hello":"world",
}', '1', '{2}');""").format("yada1","yada2","yada3")
我得到一致的错误KeyError '\n "Hello"
并追溯指向 .format()
的行。
当我删除 format
时一切正常,但我需要它来动态输入参数。
(最初它位于一个循环中)
您需要将非占位符的 {
和 }
字符加倍:
text = dedent("""\
yada yada '1' ('2','3',4')
('{0}', Null, '{1}',
'{{
"Hello":"world",
}}', '1', '{2}');""").format("yada1","yada2","yada3")
否则 Python 会看到 {\n "Hello":"world",\n}
占位符,:
之前的部分是占位符名称。
来自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 }}
.
(强调我的)。
当尝试 运行 一个包含以下用于生成文本块的代码的脚本时:
from textwrap import dedent
text = dedent("""\
yada yada '1' ('2','3',4')
('{0}', Null, '{1}',
'{
"Hello":"world",
}', '1', '{2}');""").format("yada1","yada2","yada3")
我得到一致的错误KeyError '\n "Hello"
并追溯指向 .format()
的行。
当我删除 format
时一切正常,但我需要它来动态输入参数。
(最初它位于一个循环中)
您需要将非占位符的 {
和 }
字符加倍:
text = dedent("""\
yada yada '1' ('2','3',4')
('{0}', Null, '{1}',
'{{
"Hello":"world",
}}', '1', '{2}');""").format("yada1","yada2","yada3")
否则 Python 会看到 {\n "Hello":"world",\n}
占位符,:
之前的部分是占位符名称。
来自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}}
.
(强调我的)。