[Python] str.format()

str.format()

How did I encounter this?

While refactoring the logic of sending queries to Wikidata, I realized that the function to send queries to Wikidata to search for games can be reused with different queries. However, there was an issue that SPRAQLWrapper's setQuery() doesn't support parameterized queries where placeholders (%s) can be used while providing a tuple of the values. So it's important to properly insert values into the query string. SPARQL requires formatting the string manually. This is where Python’s str.format() method becomes useful.


Syntax

The str.format() method allows inserting values into a string using curly braces {} as placeholders.

Simple example

query_template = """
SELECT DISTINCT ?item ?itemLabel WHERE {{
  ?item wdt:P31 wd:Q7889;
        rdfs:label "{}"@en.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}}
"""

game_title = "God of War"
query = query_template.format(game_title)
print(query)

Generated Query

SELECT DISTINCT ?item ?itemLabel WHERE {
  ?item wdt:P31 wd:Q7889;
        rdfs:label "God of War"@en.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Example with multiple values

If a query requires multiple dynamic values, str.format() can insert them in order.

Example with Multiple Parameters

query_template = """
SELECT ?game WHERE {{
  ?game wdt:P31 wd:Q7889;
        rdfs:label "{}"@en;
        wdt:P400 "{}".
}}
"""

values = ("God of War", "PlayStation 5")
query = query_template.format(*values)
print(query)

Generated Query

SELECT ?game WHERE {
  ?game wdt:P31 wd:Q7889;
        rdfs:label "God of War"@en;
        wdt:P400 "PlayStation 5".
}

Example of index-based formatting

query_template = "Game: {0}, Platform: {1}"
query = query_template.format("God of War", "PS5")

print(query)  
# Output: Game: God of War, Platform: PS5

Example of key-based formatting

query_template = """
SELECT ?game WHERE {{
  ?game wdt:P31 wd:Q7889;
        rdfs:label "{title}"@en;
        wdt:P400 "{platform}".
}}
"""

values = {"title": "God of War", "platform": "PlayStation 5"}
query = query_template.format(**values)

print(query)

Comments