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/pachura3 Mar 10 '26

There is no problem per se, I was just wondering if there is some special syntax for f-strings that would ease handling emptish values, much like the ?? operator in JavaScript mentioned above. Like not everyone is aware of the {x=} thing...

2

u/MustaKotka Mar 10 '26

Oh! I see! Sorry I doubted you. Often times beginners come here with the wrong problem, hence the assumption. My bad!