Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
设置python字符串的格式部分_Python_String_Format - Fatal编程技术网

设置python字符串的格式部分

设置python字符串的格式部分,python,string,format,Python,String,Format,我正在使用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抛出关键错误 是否有其他选项来执

我正在使用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抛出关键错误
是否有其他选项来执行这些任务?

使用适当的数据库API

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

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

使用适当的数据库API

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

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

谢谢你的回答@KatrieleAlex。我一直在尝试使用string
.format()
方法(python2.6+)做类似的事情。你的回答引导我得出以下结论

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

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

谢谢你的回答@katrielex。我一直在尝试使用string
.format()
方法(python2.6+)做类似的事情。你的回答引导我得出以下结论

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

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

这不是Python中的数据库。这不是Python中的数据库。这个技巧很酷。我对大多数变量使用数据库API。我使用它是有道理的,但是谢谢你的建议这个技巧很酷。我对大多数变量使用数据库API。我用得很有道理,但谢谢你的建议