【问题标题】:Python string formatting issue with curly braces ("{" and "}")大括号(“{”和“}”)的Python字符串格式问题
【发布时间】:2020-08-29 20:35:49
【问题描述】:

我有一个 GraphQL 查询字符串

query = """
        {
          scripts(developers: "1") {
          
          ...
          ...
          }
        }
    """

问。如何使用 Python 字符串格式化技术更改 developers 的值?

到目前为止我已经尝试过,

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'

【问题讨论】:

    标签: python python-3.x string-formatting f-string


    【解决方案1】:

    使用双花括号而不是单花括号在 f 字符串中编写文字花括号:

    dev_id = 1
    query = f"""
            {{
              scripts(developers: "{dev_id}") {{
              
              ...
              ...
              }}
            }}
        """
    print(query)
    #        {
    #          scripts(developers: "1") {
    #          
    #          ...
    #          ...
    #          }
    #        }
        
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2015-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 2020-08-17
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        相关资源
        最近更新 更多