含有空格和“时出现按键错误 " 在多行 f 字符串中

问题描述 投票:0回答:1

尝试使用 f 字符串在 python 中格式化 SPARQL 查询,以便从模板构建不同的查询, 但当我尝试格式化多行字符串时,我遇到了KeyError

query = f'''SELECT ?age
WHERE {{
  wd:{0} wdt:{1} ?birthdate.
  BIND(now() - ?birthdate AS ?age)
}}'''
print(query.format('Q84','P1082'))
KeyError: '\n           wd'

任何想法都有帮助,我不想逐行拆分查询。

python string sparql multiline f-string
1个回答
-1
投票

您需要将所有牙套加倍。 f 字符串和对结果字符串调用的

format
方法都会将
{{
}}
分别减少为
{
}
。因此,对于结果中想要的每个文字
{
,您需要 four
{

真的,

query
不包含查询,而是查询模板

>>> query = f'''SELECT ?age
... WHERE {{{{
... wd:{{0}} wdt:{{1}} ?birthdate.
... BIND(now() - ?birthdate AS ?age)
... }}}}'''
>>> print(query)
SELECT ?age
WHERE {{
wd:{0} wdt:{1} ?birthdate.
BIND(now() - ?birthdate AS ?age)
}}
>>> print(query.format('Q84', 'P'))
SELECT ?age
WHERE {
wd:Q84 wdt:P ?birthdate.
BIND(now() - ?birthdate AS ?age)
}
© www.soinside.com 2019 - 2024. All rights reserved.