Python 花括号(“{”和“}”)的字符串格式问题
Python string formatting issue with curly braces ("{" and "}")
我有一个 GraphQL 查询字符串作为
query = """
{
scripts(developers: "1") {
...
...
}
}
"""
Q. 如何使用 Python 字符串格式化技术更改 developers
的值?
到目前为止我已经尝试了什么,
1.using f-string
In [1]: query = f"""
...: {
...: scripts(developers: "1") {
...:
...: ...
...: ...
...: }
...: }
...: """
File "<fstring>", line 2
scripts(developers: "1") {
^
SyntaxError: invalid syntax
2.using.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-string 中写入文字 curly-brace:
dev_id = 1
query = f"""
{{
scripts(developers: "{dev_id}") {{
...
...
}}
}}
"""
print(query)
# {
# scripts(developers: "1") {
#
# ...
# ...
# }
# }
对于 f-string/format,您必须每隔 curly-brace 加倍才能逃脱它。
您可以尝试使用 %-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})
我有一个 GraphQL 查询字符串作为
query = """
{
scripts(developers: "1") {
...
...
}
}
"""
Q. 如何使用 Python 字符串格式化技术更改 developers
的值?
到目前为止我已经尝试了什么,
1.using f-string
In [1]: query = f"""
...: {
...: scripts(developers: "1") {
...:
...: ...
...: ...
...: }
...: }
...: """
File "<fstring>", line 2
scripts(developers: "1") {
^
SyntaxError: invalid syntax
2.using.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-string 中写入文字 curly-brace:
dev_id = 1
query = f"""
{{
scripts(developers: "{dev_id}") {{
...
...
}}
}}
"""
print(query)
# {
# scripts(developers: "1") {
#
# ...
# ...
# }
# }
对于 f-string/format,您必须每隔 curly-brace 加倍才能逃脱它。
您可以尝试使用 %-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})