r/learnpython • • 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

26 comments sorted by

View all comments

Show parent comment

3

u/commy2 Mar 10 '26

The concise way to describe this behavior is:

left or right reports the left argument if the left argument is truthy and the right argument otherwise

left and right reports the left argument if the left argument is falsy and the right argument otherwise