简体   繁体   中英

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?

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.

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, eg:

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.

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.

您也可以改用 zfill 方法:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM