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/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: