What's the purpose of f'strings?
python - f-string syntax for unpacking a list with brace suppression - Stack Overflow
How to use f string format without changing content of string?
New to Python, f string error
Videos
Hello i am a very very beginner coder. I’m in a beginner python class and I feel like the text books just throws stuff at concepts. Why are f’strings important? If I’m understanding it right I feel like the same output could get accomplished in a different way.
Shortest solution
Just add a comma after the unpacked list.
>>> a = [1, 2, 3]
>>> print(f"Unpacked list: {*a,}")
Unpacked list: (1, 2, 3)
There is a longer explanation to this syntax in this thread.
Caveat
With this solution is that we do not have much control over the output formatting. We are stuck with whatever format returns, which is actually (and suprisingly) the result from tuple.__repr__. So the parenthesis that we get might be misleading, since we actually had a list, and not a tuple.
If this is too bad to put up with, I would recommend using the approach suggested by Zero Piraeus:
>>> a = [1, 2, 3]
>>> print(f'Unpacked list: {" ".join(str(i) for i in a)}')
This gives us the flexibility to format the list as we wish.
Since any valid Python expression is allowed inside the braces in an f-string, you can simply use str.join() to produce the result you want:
>>> a = [1, 'a', 3, 'b']
>>> f'unpack a list: {" ".join(str(x) for x in a)}'
'unpack a list: 1 a 3 b'
You could of course also write a helper function, if your real-world use case makes the above more verbose than you'd like:
def unpack(s):
return " ".join(map(str, s)) # map(), just for kicks
>>> f'unpack a list: {unpack(a)}'
'unpack a list: 1 a 3 b'