Unpacking lists in a f string

David Lowry-Duda david at lowryduda.com
Wed Feb 9 11:00:02 EST 2022


> l1=['a','b','c']
> l2=['j','k','l']
> 
> I want to build a string like this
> "foo a j, b k, c l bar"
> Is it possible to achieve this with f strings or any other 
> simple/efficient way?

Here is a small list of things that want to be done (and natural ways to 
perform them)

1. pair items in the lists (using list comprehension),
2. format the pairs (using an f-string),
3. separate the pairs with commas (using join), and
4. incorporate surrounding "foo" "bar" text. (using an f-string)

It would be possible to have

    print(f"foo {', '.join(f'{first} {second}' for first, second in zip(l1, l2))} bar")

But I find nested f-strings to be confusing, and avoid them. This is a 
case where I actually prefer format.

    print("foo {} bar".format(
        ', '.join(f'{first} {second}' for first, second in zip(l1, l2))
    ))

It's still a one-liner, but it's a one liner that I find easier to 
parse. Or perhaps I would explicitly construct the string first and then 
use it?

    innerstr = ', '.join(f'{first} {second} for first, second in zip(l1, l2))
    print(f"foo {innerstr} bar")

These ideas are what feel natural to me.

- DLD


More information about the Python-list mailing list