使用Format()在Python中动态字符串替换

hen*_*000 1 python string dictionary

string.format()当参数可以变化时,有没有办法动态格式化字符串?我想写一个函数,其中输入是一个SQL字符串和一个名称 - 值对的字典; 两种输入都可以变化.

例如,SQL字符串可能是

"select * from students where school={schoolArg} and age={ageArg}"
Run Code Online (Sandbox Code Playgroud)

随着字典 {schoolArg: "some school", ageArg: 10}

另一个SQL字符串可能是

"select * from teachers where class={classArg}"
Run Code Online (Sandbox Code Playgroud)

随着字典 {classArg: "history"}

...等等.

我可以string.replace()毫无问题地使用.但是有可能使用string.format(),事先不知道参数吗?

jon*_*rpe 5

请注意,您使用的任何数据库包都已包含此功能,与使用基本字符串格式相比,它将更加健壮(例如适当的引用/转义(非常糟糕)和SQL注入(非常糟糕)).

请参阅例如如何在Python中使用SQL语句中的变量?

不要自己滚动,使用数据库API.


话虽如此,你几乎已经完成了它:

>>> "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'
Run Code Online (Sandbox Code Playgroud)

(如果语法不熟悉,请参阅**(双星)和*(星)对参数做什么?)

请注意,为了强调上述要点,您尚未正确引用模板字符串,因此输出不是有效的SQL查询.