格式化python字符串的一部分

Ido*_*dok 1 python string format

我正在使用python 2.7我在python中编写了一些查询

q = '''
select * from users where user_name = %(user_name)s and  user_email = %(user_email)s
'''
Run Code Online (Sandbox Code Playgroud)

我想分两步格式化字符串:

q2 = q % {'user_name':'david'}
q3 = q2 % {'user_email':'sss@sss.com'}
Run Code Online (Sandbox Code Playgroud)

我写的例子不起作用.python throws KeyError有没有其他选项来执行这些任务?

Kat*_*iel 7

使用适当的数据库API.

也就是说,如果您知道第一遍中将省略哪些键,您可以执行以下操作:

>>> "%(a)s and %%(b)s" % {'a': 1}
'1 and %(b)s'
>>> _ % {'b': 2}
'1 and 2'
Run Code Online (Sandbox Code Playgroud)