Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inserting Python Variable in Sparql

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading