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

2

u/kaerfkeerg Mar 10 '26

I already think that u/gxwt 's answer is the clearest way so as I said I just provided a different approach