简体   繁体   中英

Dynamic String Replacement in Python using Format()

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM