大括号“ {”和“}”的Python字符串格式问题

问题描述

我有一个GraphQL查询字符串

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

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

到目前为止我尝试过的,

1。使用f字符串

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'

解决方法

使用double-curly-brace而不是single-curly-brace在f字符串中写一个字面大括号:

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

使用f字符串/格式,您必须将每个花括号都翻倍才能逃脱它。

您可以尝试使用%格式:

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...