pythonf-stringiterable-unpacking

Python f-string equivalent of iterable unpacking by print instruction


print can nicely unpack a tuple removing brackets and commas, e.g.

a = (0, -1, 1)
print(*a)

produces 0 -1 1. Trying the same with f-strings fails:

print(f'{*a}')

The closest f-string option I found is:

print(f'{*a,}'.replace(',', '').replace('(', '').replace(')', ''))

Is there a more direct way to get 0 -1 1 from *a using f-strings?


Solution

  • The most straightforward way I could come up with is the join method for strings.

    >>> a = ('x','y','z')
    >>> print(f'{" ".join(a)}')
    x y z
    

    If your tuple elements aren't strings, they have to be converted (if possible).

    >>> a = (0,-1,1)
    >>> print(f'{" ".join(map(str, a))}')
    0 -1 1