【问题标题】:Add variable to a triple quote string issue [duplicate]将变量添加到三引号字符串问题[重复]
【发布时间】:2021-08-19 13:20:07
【问题描述】:

我在 Python 中运行了以下代码:

configuration_str= """
    configuration={
                "query": {
                "query": "CALL `{0}.{1}.{2}`(); ",
                "useLegacySql": False,
            }
            },

""".format("server_name", "dataset_name", "sp_name")

我收到以下错误:

Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
KeyError: '\n                    "query"'

问题是什么以及如何解决?

【问题讨论】:

  • 你需要转义不是应该是str.formatted的大括号。
  • 你为什么一开始就将 Python 代码生成为字符串...?

标签: python python-3.x string


【解决方案1】:

用f字符串怎么样

server_name = 'A'
dataset_name = 'B'
sp_name ='C'

configuration_str = f"""configuration={{
                "query": {{
                "query": "CALL '{server_name}.{dataset_name}.{sp_name}'(); ",
                "useLegacySql": False,
            }}
            }}"""

print(configuration_str)

输出

configuration={
                "query": {
                "query": "CALL 'A.B.C'(); ",
                "useLegacySql": False,
            }
            }

【讨论】:

  • f-strings 和 OP 的代码有同样的问题,你只是默默地修复了,没有解释…
  • 非常感谢您的帮助。
猜你喜欢
  • 2016-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 2011-04-23
  • 1970-01-01
相关资源
最近更新 更多