Home > Software design >  Python string formatting from list after completed for loop
Python string formatting from list after completed for loop

Time:09-28

I am building a sql query from several lists and dictionaries of variables. Currently I format each string within the for loops like this:

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.

Instead of formatting these lines within the for loop, I would like to build the parameterized query, and then format later. How can I do this?

CodePudding user response:

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)
  • Related