-1

I'm trying to substitute a variable called id in the below string

query = '''SELECT ?item ?itemLabel WHERE {?item wdt:P279* wd:Q7930989. SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }}'''

I'd like to do something like

id = "wd:Q7930989"    
query = f'''SELECT ?item ?itemLabel WHERE {?item wdt:P279* {id}. SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }}'''

When I try to run the above code, I run into errors like KeyError: '?item wdt’ I think this might be due to the brackets already within the string. I’d ideally like a way to escape these brackets so that I can insert {id} into the string.

Any ideas?

gatech-kid
  • 67
  • 8
  • I didn't downvote your question, but it sure needs a bit of clarification - I posted an answer trying to cover what you'd like to achieve. – Barney Szabolcs Feb 03 '21 at 14:37
  • 6
    Do *not* build a SQL query using string formatting operations. – chepner Feb 03 '21 at 14:38
  • I can't understand the question. Show *exactly* what you start with, *exactly* what you believe you want to end up with, and explain *exactly* why you think it will be useful to end up with that. – Karl Knechtel Feb 03 '21 at 14:39

1 Answers1

0

Try and break the statement into simpler components. It looks cleaner which would be the point of using f-strings.

Otherwise, if you need to escape "{" in f-string, you can use "{{". Eg.

s = "{{{0}" # is "{0"
s = "{0}}}" # is "0}"
Barney Szabolcs
  • 11,846
  • 12
  • 66
  • 91