Search code examples
pythonpython-3.xf-string

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.


Solution

  • 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.