Search code examples
pythonstring-formatting

how do I map/assign a list of format strings to a list of values when printing?


Scenario: I've got a large list of mixed-type values: strings, floats, ints, etc. I want to print these in various different output formats. It would be much easier if I could keep a separate list of formats and then map the list of formats to the list of values.
As a simple, specific example imagine that I have three values

vals = [45.6789, 155.01, "purple"]

and I want to print the first number as a float of width 2 rounded to two decimal places, the second number as width of four rounded to a whole number, and the third string as left-justified with a width of 10 chars. The corresponding f-strings formats would be:

list_of_formats = [':2.2f', ':4.0f', ':10']

The equivalent behavior I want would be if I did:

print(f'{vals[0]:2.2f}')
print(f'{vals[1]:4.0f}')
print(f'{vals[2]:10}')

Now... how do I go about assigning / mapping / zipping / lambda-ing these things together in some kind of loop or comprehension? I'm 99% sure this capability exists (because python does EVERYTHING like this, right?) but I'm struggling with the syntax and figuring out whether these formatting codes are treated as strings, or some special type, or something else, and where to put the 'f' and the quotes and the brackets and all that. I looked for an example of this and couldn't find one, but totally possible that's because I don't know the right nouns to use...


Solution

  • I should have mentioned that I was trying to use f-strings and avoid format() -- but... Ah-HAH! The secret knock is that you can nest the braces within a format string so you interpolate both the value AND the format. My final answer looked like this:

    outstr = ','.join( [f'{val:{fmt}}' for val,fmt in zip(outrow,fmts)]  )
    ##  this nested brace!    ^^^^^^^
    
    print(outstr)