我正在使用 python 2.7 我正在用 python 编写一些查询
q = '''
select * from users where user_name = %(user_name)s and user_email = %(user_email)s
'''
我想分两步格式化字符串 像这样的东西:
q2 = q % {'user_name':'david'}
q3 = q2 % {'user_email':'sss@sss.com'}
我写的例子不工作。 python抛出KeyError 是否有任何其他选项来执行这些任务?
最佳答案
使用适当的数据库 API。
也就是说,如果您知道在第一遍中将省略哪些键,您可以这样做:
>>> "%(a)s and %%(b)s" % {'a': 1}
'1 and %(b)s'
>>> _ % {'b': 2}
'1 and 2'
关于python - 格式化python字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9455534/