【问题标题】:format part of python string格式化python字符串的一部分
【发布时间】:2012-02-26 17:53:45
【问题描述】:

我正在使用 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 是否有其他选项可以执行这些任务?

【问题讨论】:

  • 这不是你在 Python 中做数据库的方式。

标签: python string format


【解决方案1】:

使用适当的数据库 API。

也就是说,如果您知道在第一遍中将省略哪些键,您可以这样做:

>>> "%(a)s and %%(b)s" % {'a': 1}
'1 and %(b)s'
>>> _ % {'b': 2}
'1 and 2'

【讨论】:

  • 这个技巧很酷。我对大多数变量使用数据库 API。我正在使用它,但感谢您的建议
【解决方案2】:

感谢您的回答@katrielalex。我一直在尝试使用字符串.format() 方法(python2.6+)做类似的事情。您的回答引导我提出以下建议。

>>> s="{a} and {{b}}"
'{a} and {{b}}'
>>> s.format( a = 1 )
'1 and {b}'
>>> _.format( b = 2 )
'1 and 2' 

我希望它对所有想要使用新功能的人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 2019-11-28
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    相关资源
    最近更新 更多