pythonsparqlsparqlwrapperknowledge-graph

How can we use a python string variable in a SPARQL query?


I want to use python string variables in my SPARQL query without an IRI (for the sake of looping through a list of variables etc. I tried the code below but it doesn't seem to work.

Please ignore the prefixes etc. I just changed them for the sake of posting my code here and they do not really affect the error or question.

This is what I tried:

variable = "apple"

knows_query = """ 
PREFIX example: <http://www.example.com>
SELECT DISTINCT ?s
WHERE {
    ?s rdfs:label | example:someExample | example:anotherExample """+variable+""" .
}"""

This gives the error:

ParseException: Expected {SelectQuery | ConstructQuery | DescribeQuery | AskQuery}, found '?'  (at char 201), (line:6, col:9)

I have tried "+variable+" but it doesn't work either.

The above code should achieve what this code achieves:

knows_query = """ 
PREFIX example: <http://www.example.com>
SELECT DISTINCT ?s
WHERE {
    ?s rdfs:label | example:someExample | example:anotherExample "apple" .
}"""

I also tried How to pass python variable to sparql query? but it doesn't seem to work for some reason, giving a similar error.


Solution

  • Your expected query string has the word apple within quotes, whereas your query simply includes it in without the quotes. (If in doubt, print it out.)

    You must add quotes before and after the word occurs.

    I'm using Python f-strings, available in Python 3.6 and above, which is much better for readability and code maintenance.

    knows_query = f""" 
    PREFIX example: <http://www.example.com>
    SELECT DISTINCT ?s
    WHERE {
        ?s rdfs:label | example:someExample | example:anotherExample "{variable}" .
    }"""