If I have an f-string where one of the parameters may be None
, is there a way to automatically omit it from the string?
f'{first_name} {prefix} {last_name}'
If prefix
is None
then this string will render as Arnold None Weber
.
I tried f'{first_name} {prefix or ''} {last_name}'
but that's a syntax error.
I tried f'{first_name} {prefix or ''} {last_name}' but that's a syntax error.
The only reason it's a syntax error is that you tried to put single quotes inside single quotes. All of the usual ways of fixing it will work:
f'{first_name} {prefix or ""} {last_name}'
f"{first_name} {prefix or ''} {last_name}"
f"""{first_name} {prefix or ''} {last_name}"""
However, notice that this doesn't quite do what you want. You won't get Arnold Weber
, but Arnold Weber
, because the spaces on either end aren't conditional. You could do something like this:
f'{first_name} {prefix+" " if prefix else ""}{last_name}'
f'{first_name} {prefix or ""}{" " if prefix else ""}{last_name}'
… but at that point, I don't think you're getting the conciseness and readability benefits of f-strings anymore. Maybe consider something different, like:
' '.join(part for part in (first_name, prefix, last_name) if part)
' '.join(filter(None, (first_name, prefix, last_name)))
Not that this is shorter—but the logic is a lot clearer.
Of course it's a syntax error; you broke your string.
f'{first_name} {prefix or ""} {last_name}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With