Home > other >  How to use a programatically-generated f-string
How to use a programatically-generated f-string

Time:12-11

I have a nested list which always has the same number of columns per row, but the number of columns can vary depending on user input. I would like to nicely format the output into columns using string formatting. Example:

grid = [['parent', '', ''],
 ['child1', 'child2', '',],
 ['', 'grandchild1', 'grandchild2']]

If I hard-code the f-string formatting, it works fine:

for col1, col2, col3 in grid:
    print (f"{col1:<20}{col2:<20}{col3:<20}")

produces the desired result:

parent                                                      
child1              child2                                  
                    grandchild1         grandchild2         

What I'm trying to do is programmatically build and then use the f-string. I can programmatically build the f-string:

f_string = ''
for col_index, col in enumerate(grid[0]):
    f_string  = "{row["   str(col_index)   "]:<20}"

for row in grid:
    print (f_string)

produces the desired f-string

f_string='{row[0]:<20}{row[1]:<20}{row[2]:<20}'

but I can't figure out how to use the built f-string.

What I have outputs the f-string itself, not the f-string applied to the data in grid:

{row[0]:<20}{row[1]:<20}{row[2]:<20}
{row[0]:<20}{row[1]:<20}{row[2]:<20}
{row[0]:<20}{row[1]:<20}{row[2]:<20}

CodePudding user response:

Use the format method:

print(f_string.format(row=[1,2,3]))

1                   2                   3

In a loop:

for row in grid:
    print(f_string.format(row=row))
  • Related