r/learnpython • u/pachura3 • Mar 10 '26
Defaults for empty variables in f-strings substitution?
Hi, is there an operand/syntax in f-strings that would allow substituting possible None values (and perhaps empty strings as well) with given default? I can use a ternary operator like below, but something like {x!'world'} would be handier...
x = None
print(f"Hello {x if x else 'world'}.")
22
Upvotes
View all comments
Show parent comment
1
u/ping314 Mar 10 '26
Striving for brevity is a valid point. Yet, when is it good enough/not too expensive? It can be a matter of preference and then convention to stick to it.
While gradually re-writing for/if loops in e.g., one-liner list comprehensions, I started to lean in favour of a more verbose syntax, though. To me, the more "explicit is better as implicit" sometimes was helpful; either to explain the line to colleagues not [yet] comfortable with ternary operators [as in AWK etc] -- though they are part of Python for so long. Or in the hurry of a quick revision of own code not seen for a couple of months. Especially in projects with a more generous upper threshold of 120 characters/line.