pythonstringsparqlmultilinef-string

Key Error when having spaces and "\n" in multiline f-string


Trying to format SPARQL queries in python using f-strings in order to build different queries from a template, but i'm getting KeyError when i try to format a multiline string:

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

Any idea helps, i'd prefer not to split the queries line by line.


Solution

  • You need to double all your braces. Both the f-string and the format method called on the resulting string will reduce {{ and }} to { and }, respectively. So for each literal { you want in the result, you need four {.

    Really, query does not contain a query, but a query template.

    >>> 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)
    }
    

    (I assume you are aware of the dangers of creating parameterized queries via string interpolation, and have taken the necessary precautions to sanitize the inputs to query.format.)

    The simplest thing to do, though, is to use an f-string or the format method, rather than both. You don't need two rounds of substitution.