首页 > 解决方案 > 大括号(“{”和“}”)的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'

标签: pythonpython-3.xstring-formattingf-string

解决方案


使用 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})

推荐阅读