2

Is there a way to dynamically format a string with string.format(), when the arguments can vary? I want to write a function where the inputs are a SQL string and a dictionary of name-value pairs; both inputs can vary.

So for example, a SQL string might be

"select * from students where school={schoolArg} and age={ageArg}"

with the dictionary being {schoolArg: "some school", ageArg: 10}

Another SQL string might be

"select * from teachers where class={classArg}"

with the dictionary being {classArg: "history"}

...and so on.

I can use string.replace() without problems. But is it possible to use string.format(), where the arguments is not known in advance?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
henrykodev
  • 2,964
  • 3
  • 27
  • 39

1 Answers1

5

Note that whatever database package you are using will already contain functionality for this, which will be much more robust (to e.g. appropriate quoting/escaping (quite bad) and SQL injection (very bad)) than using basic string formatting.

See e.g. How to use variables in SQL statement in Python?

Don't roll your own, use the database API.


That being said, you've almost done it already:

>>> "select * from students where school={schoolArg} and age={ageArg}".format(**{"schoolArg": "some school", "ageArg": 10})
'select * from students where school=some school and age=10'
>>> "select * from teachers where class={classArg}".format(**{"classArg": "history"})
'select * from teachers where class=history'

(If the syntax is unfamiliar, see What does ** (double star) and * (star) do for parameters?)

Note that, to reinforce the point above, you haven't correctly quoted your template string, so the output isn't a valid SQL query.

Community
  • 1
  • 1
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437