I'm learning python and when I was reading about formatted string literals, I noticed something in the reference that I cannot understand. Here is the syntax of formatted string literals:
f_string ::= (literal_char | "{{" | "}}" | replacement_field)*
replacement_field ::= "{" f_expression ["="] ["!" conversion] [":" format_spec] "}"
f_expression ::= (conditional_expression | "*" or_expr)
("," conditional_expression | "," "*" or_expr)* [","]
| yield_expression
conversion ::= "s" | "r" | "a"
format_spec ::= (literal_char | NULL | replacement_field)*
literal_char ::= <any code point except "{", "}" or NULL>
As you see, these are 3 formats for f_expression
. The conditional_expression
one is easy to understand and here is an example:
a=[1, 2, 3]
print(f'test: {"a" if 4 in a else None}')
But I cannot understand next 2 correctly. First one is "*" or_expr
, which means it is an expression that needs to start with *
. I cannot write any code that matches this syntax and all codes like:
print(f"test: {(*a)}")
gives me an error which says I cannot use starred expression here. The next one is yield_expression
which I somehow get it working like this:
def testit():
print(f'test: {yield 125}')
for x in testit():
print(x)
which prints:
125
test: None
I don't understand what is use of this mode inside formatted string literals at all. Can you tell me what is the usage of these 2 expressions in formatted string literals?