Home > front end >  Inserting Python Variable in Sparql
Inserting Python Variable in Sparql

Time:12-02

I have a string variable i want to pass in my sparql query and i cant 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 doesnt work and i get an error. The query is correct as it works if i manualy enter the name when i replace title

CodePudding user response:

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.

  • Related