Reputation: 4132
I'm using python 2.7 I'm writing some query in python
q = '''
select * from users where user_name = %(user_name)s and user_email = %(user_email)s
'''
I want to format the string in two step something like :
q2 = q % {'user_name':'david'}
q3 = q2 % {'user_email':'[email protected]'}
The example i wrote is not working. python throws KeyError is there any other option to perform those tasks?
Upvotes: 1
Views: 1951
Reputation: 455
Thanks for your answer @katrielalex. I've been trying to do something similar using the string .format()
method (python2.6+). Your answer guided me to come up with the following.
>>> s="{a} and {{b}}"
'{a} and {{b}}'
>>> s.format( a = 1 )
'1 and {b}'
>>> _.format( b = 2 )
'1 and 2'
I hope it helps all of those who want to use the new functionality.
Upvotes: 4
Reputation: 123632
Use a proper database API.
That said, if you know which keys will be omitted in the first pass, you can do:
>>> "%(a)s and %%(b)s" % {'a': 1}
'1 and %(b)s'
>>> _ % {'b': 2}
'1 and 2'
Upvotes: 7