Python 自动将参数格式化为字符串
我正在编写一个函数,它接受一些参数并构建一个SQL查询字符串。目前,我已将每个关键字参数按名称分配给字符串,我认为必须有一种更简单的方法来自动格式化字符串中预期的关键字参数。我想知道如果参数名称匹配,是否可以自动格式化(或分配)查询字符串的关键字参数 以下是我目前的职能:Python 自动将参数格式化为字符串,python,Python,我正在编写一个函数,它接受一些参数并构建一个SQL查询字符串。目前,我已将每个关键字参数按名称分配给字符串,我认为必须有一种更简单的方法来自动格式化字符串中预期的关键字参数。我想知道如果参数名称匹配,是否可以自动格式化(或分配)查询字符串的关键字参数 以下是我目前的职能: def create_query( who_id, what_id=None, owner_id=None, subject, description, due_date,
def create_query(
who_id,
what_id=None,
owner_id=None,
subject,
description,
due_date,
is_closed=False,
is_priority=False,
is_reminder=True,
):
query_str = """
'WhoId':'{who_id}',
'Subject':'{subject}',
'Description':'{description}',
'ActivityDate':'{due_date}',
'IsClosed':'{is_closed}',
'IsPriority':'{is_priority}',
'IsReminderSet':'{is_reminder}',
""".format(
who_id=who_id,
subject=subject, # Mapping each of these to the
description=description, # identically named variable
due_date=due_date, # seems dumb
is_closed=is_closed,
is_priority=is_priority,
is_reminder=is_reminder,
)
我想要更像这样的东西:
def create_query(**kwargs):
query_string = """
'WhoId':'{who_id}',
'Subject':'{subject}',
'Description':'{description}',
...
""".format(
for key in **kwargs:
if key == << one of the {keyword} variables in query_string >>:
key = << the matching variable in query_string >>
def create_查询(**kwargs):
查询字符串“”
“WhoId”:“{who_id}”,
“主题”:“{Subject}”,
'Description':'{Description}',
...
“”格式(
对于输入**kwargs:
如果键==>:
键=>
可以这样使用:
create_query(who_id=123, subject="Boss", description="he's bossy",
will_be_ignored="really?")
印刷品:
'WhoId':'123',
'Subject':'Boss',
'Description':'he is bossy',
...
'WhoId':'{123}','Description':'{he's bossy}'
请注意,我输入的附加参数将被忽略。它将被忽略。您不必自己过滤
但最好不要自己构建查询字符串。让数据库连接器来处理。例如,如果我的示例说“他很霸道”然后这将中断查询,因为它使用“
作为分隔符。您的数据库连接器应允许您使用占位符和值为其提供查询,然后用值正确替换占位符
备选方案:
def create_query(**kwargs):
parameters = (('WhoId', 'who_id'),
('Subject','subject'),
('Description', 'description'))
query_string = ','.join(r"'{}':'{{{}}}'".format(name, kwargs[id])
for name, id in parameters
if id in kwargs)
print(query_string)
create_query(who_id=123, description="he's bossy",
will_be_ignored="really?")
印刷品:
'WhoId':'123',
'Subject':'Boss',
'Description':'he is bossy',
...
'WhoId':'{123}','Description':'{he's bossy}'
感谢您在这方面的帮助。您建议如何处理可选的KWARG?例如,某些项可能与查询无关,但我希望提供一个选项将它们构建到查询中。在本例中,如果我没有传递一个值来进行说明,则会出现一个键错误。同意这不是b的最佳选择生成查询字符串,但我正在使用Salesforce API,因此除了对引号和双引号进行清理外,我不知道如何处理此问题。@JoeFusaro您的意思是您想要默认值,还是根本不希望它们出现在最终查询字符串中?首选项是它们根本不在最终查询字符串中,而是默认值es是可以的。不确定什么是最佳的。我考虑了基于kwargs中是否包含它们的连接(例如if kwargs['description']:query_string+='','description':'{description}'..),但这看起来很混乱。@JoeFusaro在这一点上,您最好不要这样编写格式字符串。请查看“备选方案”“我只是补充了我的答案。