Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 418
planetp Avatar asked Jan 27 '17 14:01

planetp


People also ask

How do you use an F string in a list in Python?

text2 = F"This is the {second} string." As you can see in the example, curly braces have been used twice in f-strings. Expressions and variables inside curly braces within f-strings are evaluated by Python and then they are substituted with the results returned by the original expressions.

How do you convert a list to a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

What is the use of f {} in Python?

The most obvious usage of F strings is to interpolate simple values inside of throws, output, what have you. This is done using the {} syntax and just providing that values name. The value will also be implicitly casted if it is possible, of course.

Can you call a function in an F string?

We can also call functions in f-strings. The example calls a custom function in the f-string.


1 Answers

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.

like image 83
Ma0 Avatar answered Oct 12 '22 23:10

Ma0