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?
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.
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.
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.
We can also call functions in f-strings. The example calls a custom function in the 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With