Avoiding None in f-string
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}'