Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding None in f-string

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.

like image 654
voodoo-burger Avatar asked Jul 11 '18 22:07

voodoo-burger


2 Answers

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.

like image 59
abarnert Avatar answered Oct 21 '22 13:10

abarnert


Of course it's a syntax error; you broke your string.

f'{first_name} {prefix or ""} {last_name}'
like image 45
Ignacio Vazquez-Abrams Avatar answered Oct 21 '22 12:10

Ignacio Vazquez-Abrams