python - 大括号(“{”和“}”)的Python字符串格式问题
问题描述
我有一个 GraphQL 查询字符串
query = """
{
scripts(developers: "1") {
...
...
}
}
"""
问:如何developers
使用 Python 字符串格式化技术更改 的值?
到目前为止我所尝试的,
1.使用f-string
In [1]: query = f"""
...: {
...: scripts(developers: "1") {
...:
...: ...
...: ...
...: }
...: }
...: """
File "<fstring>", line 2
scripts(developers: "1") {
^
SyntaxError: invalid syntax
2.使用.format()
方法
In [2]: query = """
...: {
...: scripts(developers: "{dev_id}") {
...:
...: ...
...: ...
...: }
...: }
...: """
...:
...: query.format(dev_id=123)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-2-058a3791fe41> in <module>
9 """
10
---> 11 query.format(dev_id=123)
KeyError: '\n scripts(developers'
解决方案
使用 f-string/format,您必须将每个花括号加倍才能转义它。
您可以尝试使用 %-formatting:
query = """
{
script(developers: %s) {
...
}
}
""" % 1
或者更好地查看像https://github.com/graphql-python/gql这样的 graphql 库
query = gql("""
{
script(developers: $dev) {
...
}
}
""")
client.execute(client.execute(query, variable_values={'dev': 1})
推荐阅读
- python - 编辑每行文本文件的最后一个元素
- python - DATA_UPLOAD_MAX_MEMORY_SIZE 被 django 2.2.6 覆盖
- java - 如何将属性文件中的空值添加到 Map
- android - 'java.lang.Class java.lang.Object.getClass()' 在空对象引用上保存数据
- excel - Excel:根据另一个单元格的内容动态地将标准检查添加到计数中
- android - 我需要建议如何在 android 中实现这种 UI?
- angular8 - Angular 8 中的 HttpInterceptor 问题 - 未触发 HTTPInterceptor
- javascript - 根据参数注入正确的服务
- java - Gradle 多模块。使用来自另一个模块的 EventListener 检查第一个模块的上下文
- xslt - XPath 根据子值选择元素