planetp
planetp

Reputation: 16113

How to interpolate a list into an f-string in Python?

Say I have a function

def foo(): return [1, 2, 3]

I want to interpolate the result of the function into a string to get "001 002 003". I've tried this:

f"{*foo():03d 03d 03d}"

But it produced SyntaxError: can't use starred expression here. Can I do this using an f-string?

Upvotes: 18

Views: 12889

Answers (5)

Eugene Yarmash
Eugene Yarmash

Reputation: 150031

Starred expressions are only allowed in few specific contexts, such as function calls, list/tuple/set literals, etc. An f-string placeholder is not one of them, apparently. You could format each element individually and join the strings, e.g.:

lst = foo()
s = ' '.join(f'{x:03d}' for x in lst)  # '001 002 003'

Generally, to format multiple values you have to use a separate placeholder for each value.

Upvotes: 7

user11191688
user11191688

Reputation: 11

You can also use the zfill method instead:

s_repr=" ".join([str(x).zfill(3) for x in foo()]) #not very PEP8 =S

Upvotes: 1

divenex
divenex

Reputation: 17236

For lists, f-strings do not seem to add much to what was already possible without them. An alternative, slightly simpler, solution without f-strings and without .join, which works for any list length, is the following

a = foo()
str_repr = ("{:03d} "*len(a)).format(*a)
print(str_repr)  # prints: 001 002 003

Upvotes: 1

L3viathan
L3viathan

Reputation: 27333

The * operator (similar rules exist for **) can only be used inside:

  • a function call: foo(*bar)
  • a list, tuple, or set literal: ['foo', *bar]
  • an assignment: foo, *bar = range(10)

It is not an expression and can therefore not be used inside the braces of f-strings.

Upvotes: 3

Ma0
Ma0

Reputation: 15204

is this what you are looking for?

str_repr = ' '.join(map('{:03d}'.format, foo()))
print(str_repr)  # prints: 001 002 003

maybe the best thing about this solution is that it works with any list length and with minimal tweaking you can change the output format too.

Upvotes: 7

Related Questions