简体   繁体   English

Python 完成 for 循环后列表中的字符串格式

[英]Python string formatting from list after completed for loop

I am building a sql query from several lists and dictionaries of variables.我正在从几个变量列表和字典构建一个 sql 查询。 Currently I format each string within the for loops like this:目前我在 for 循环中格式化每个字符串,如下所示:

for plat in PLATFORM_LIST:
    for gk, gv in GENDER_MAP.items():
        for ak, av in AGE_MAP.items():
            query += line_a.format(plat=plat, gv=gv, av=av, ak=ak)
            query += line_b.format(plat=plat, gv=gv, av=av, ak=ak)
            query += line_c.format(plat=plat, gv=gv, av=av, ak=ak)

where lines a, b, and c are strings that need to be formatted with platform, gender, and age variables.其中 a、b 和 c 行是需要使用平台、性别和年龄变量进行格式化的字符串。

Instead of formatting these lines within the for loop, I would like to build the parameterized query, and then format later.我不想在 for 循环中格式化这些行,而是想构建参数化查询,然后再格式化。 How can I do this?我怎样才能做到这一点?

Change your formatting placeholders to {} rather than variable names.将格式占位符更改为{}而不是变量名称。 Then concatenate the parameters to the format list (make sure they're in the proper order).然后将参数连接到格式列表(确保它们的顺序正确)。

params = []
query_fmt = ""
for plat in PLATFORM_LIST:
    for gk, gv in GENDER_MAP.items():
        for ak, av in AGE_MAP.items():
            query_fmt += line_a + line_b + line_c
            params += [plat, gv, av, ak] * 3

query += query_fmt.format(params)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM