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

带大括号(“{”和“}”)的Python字符串格式问题,python,python-3.x,string-formatting,f-string,Python,Python 3.x,String Formatting,F String,我有一个GraphQL查询字符串作为 query = """ { scripts(developers: "1") { ... ... } } """ Q.如何使用Python字符串格式技术更改开发人员的值 我到目前为止所做的 1.使用f字符串 In [1]: query =

我有一个GraphQL查询字符串作为

query = """
        {
          scripts(developers: "1") {
          
          ...
          ...
          }
        }
    """
Q.如何使用Python字符串格式技术更改
开发人员的值

我到目前为止所做的

1.使用f字符串

In [1]: query = f""" 
   ...:         { 
   ...:           scripts(developers: "1") { 
   ...:            
   ...:           ... 
   ...:           ... 
   ...:           } 
   ...:         } 
   ...:     """                                                                                                                                                                                                    
  File "<fstring>", line 2
    scripts(developers: "1") {
                      ^
SyntaxError: invalid syntax

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

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

使用f-string/format时,必须将每个花括号加倍才能将其转义

您可以尝试使用以下格式:

query = """ 
{
  script(developers: %s) {
  ...
  }
}
""" % 1
或者最好查看graphql库,如

query = """ 
{
  script(developers: %s) {
  ...
  }
}
""" % 1
query = gql("""
{
  script(developers: $dev) {
  ...
  }
}
""")
client.execute(client.execute(query, variable_values={'dev': 1})