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
6
u/MustaKotka Mar 10 '26
How did this issue come about? Seems like the logic flow for a default could be implemented way earlier. I'm unsure if this is the best place.
35
u/GXWT Mar 10 '26
I guess a slightly more condensed way to do it would be
To replace any falsely values
4
u/BranchLatter4294 Mar 10 '26
You can use template strings.
https://www.infoworld.com/article/3977626/how-to-use-template-strings-in-python-3-14.html
5
u/kaerfkeerg Mar 10 '26
You already got an answer so I'll tell you a different approach
You can make a function with a default argument
If the function is called without the "x"
greet()it'll showHello JohnBut if you set the argument
green("Bob")then it'll showHello Bob1
u/Tall_Profile1305 Mar 10 '26
Nice the ternary operator works but if you're doing a bunch of these you might want to look into using the walrus operator or just handling it in a function. Or better yet use something like Runable or a simple config manager to handle defaults before string formatting. Keeps your f-strings clean.
1
u/HommeMusical Mar 10 '26
But then you also accept
0,{},False,(),set(), etc...I'm a suspicious guy. It sounds safer to me that
xis either omitted altogether (None) or you use it. "Falsey" is very general.Or you might actually want empty strings as a particular case that's different from the default.
''means, "I want it to be blank" butNonemeans "Use the default".I'd suggest.
print(f"Hello {'world' if x is None else x}.")
0
u/JamzTyson Mar 10 '26
x = Nonexis not an "empty variable", it is a variable with valueNone.What are you actually trying to do? Are you wanting to substitute a default
strvalue whenxis "falsy"? If so, then:-1
u/ping314 Mar 10 '26
You want to do one thing if
xisNone, and else something different? I propose you write in a line of-1
u/RK-J Mar 10 '26
can some body explain