问题
How can I insert for
loops or if
expressions inside an f-string?
I thought initially of doing something like this for if
expressions:
f'{a:{"s" if CONDITION else "??"}}'
What I would like to do though is something like:
Example 1
f'{key: value\n for key, value in dict.items()}'
result:
if dict = {'a': 1, 'b': 2}
a: 1
b: 2
or Example 2
c = 'hello'
f'{c} {name if name else "unknown"}'
result:
if name exists, e.g. name = 'Mike'
hello Mike
otherwise
hello unknown
Can this be done and if yes how?
回答1:
Both ternaries ("if
expressions") and comprehensions ("for
expressions") are allowed inside f-strings. However, they must be part of expressions that evaluate to strings. For example, key: value
is a dict pair, and f"{key}: {value}"
is required to produce a string.
>>> dct = {'a': 1, 'b': 2}
>>> newline = "\n" # \escapes are not allowed inside f-strings
>>> print(f'{newline.join(f"{key}: {value}" for key, value in dct.items())}')
a: 1
b: 2
Note that if the entire f-string is a single format expression, it is simpler to just evaluate the expression directly.
>>> print("\n".join(f"{key}: {value}" for key, value in dct.items())))
a: 1
b: 2
Expressions inside format strings still follow their regular semantics. For example, a ternary may test whether an existing name is true. It will fail if the name is not defined.
>>> c, name = "Hello", ""
>>> f'{c} {name if name else "unknown"}'
'Hello unknown'
>>> del name
>>> f'{c} {name if name else "unknown"}'
NameError: name 'name' is not defined
来源:https://stackoverflow.com/questions/59956496/f-strings-formatter-including-for-loop-or-if-conditions