Search code examples
pythonvariablessparql

Inserting python variable in SPARQL


I have a string variable I want to pass in my SPARQL query and I can't get it to work.

title = 'Good Will Hunting'

[str(s) for s, in graph.query('''
    PREFIX ddis: <http://ddis.ch/atai/> 
    PREFIX wd: <http://www.wikidata.org/entity/> 
    PREFIX wdt: <http://www.wikidata.org/prop/direct/> 
    PREFIX schema: <http://schema.org/> 
    
    SELECT ?lbl WHERE {
        ?movie rdfs:label  $title@en .
        ?movie wdt:P57 ?director .
        ?director rdfs:label ?lbl .
    }
    ''')]

It doesn't work and I get an error. The query is correct as it works if I manualy enter the name when I replace $title.


Solution

  • String interpolation in python can be achieved with the %s symbol (for string variables):

    title = 'Good Will Hunting'
    
    [str(s) for s, in graph.query('''
        PREFIX ddis: <http://ddis.ch/atai/> 
        PREFIX wd: <http://www.wikidata.org/entity/> 
        PREFIX wdt: <http://www.wikidata.org/prop/direct/> 
        PREFIX schema: <http://schema.org/> 
        
        SELECT ?lbl WHERE {
            ?movie rdfs:label "%s"@en .
            ?movie wdt:P57 ?director .
            ?director rdfs:label ?lbl .
        }
        ''' % title)]
    

    Note that I also added quotes ("%s"), that are necessary for specifying a string in SPARQL.