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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, Python makes life so much easier! Regarding using database API, I will learn/read up on that. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.