JPG*_*JPG 2 python string-formatting python-3.x f-string
我有一个 GraphQL 查询字符串
query = """
{
scripts(developers: "1") {
...
...
}
}
"""
Run Code Online (Sandbox Code Playgroud)
问:如何developers使用 Python 字符串格式化技术更改 的值?
到目前为止我所尝试过的
1.使用f字符串
In [1]: query = f"""
...: {
...: scripts(developers: "1") {
...:
...: ...
...: ...
...: }
...: }
...: """
File "<fstring>", line 2
scripts(developers: "1") {
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)
使用双花括号而不是单花括号在 f 字符串中写入文字花括号:
dev_id = 1
query = f"""
{{
scripts(developers: "{dev_id}") {{
...
...
}}
}}
"""
print(query)
# {
# scripts(developers: "1") {
#
# ...
# ...
# }
# }
Run Code Online (Sandbox Code Playgroud)