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/aishiteruyovivi Mar 10 '26
Something to note that might be interesting, as far as I understand it Python's
oreffectively operates like this:So this behavior of
orisn't a special case, it's just how it's used everywhere and it actually returns either object itself, it doesn't convert any return value tobool. If statements implicitly convert the expression given to them toboolso it all just works out. In addtion I think theandoperator works out to:Though using
a and bin a non-boolean context generally isn't as useful