gpt4 book ai didi

花括号 ("{"和 "}"的 Python 字符串格式问题)

转载 作者:行者123 更新时间:2023-12-05 08:49:37 25 4
gpt4 key购买 nike

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

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

...
...
}
}
"""

问。如何使用 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'

最佳答案

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

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

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

关于花括号 ("{"和 "}"的 Python 字符串格式问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63651556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com