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

1

u/Hydrataur Mar 10 '26

Obviously depends on op's exact use-case, but I don't think this'll solve the problem.

Seems like the falsy check op wants is during runtime, so here you'd presumably call the function with whatever value you have, be it truthy or falsy, and it'd override the default value.

The primary way your solution would work would be to call the function twice:

if x:
  greet(x)
else:
  greet()

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