Search code examples
pythonpython-3.xstring-interpolation

Conditional string interpolation


What's wrong with the syntax below? I want to assign x to {diff} short of if diff > 0 otherwise it shall be an empty string.

diff = 1
x = f"{diff 'short of' if diff > 0 else ''}"

EDIT: Based on the comment, it seems that the right way to do this would be:

x = f"{diff} short of" if diff > 0 else ""

However, I also need to put x in another string interpolation e.g.

y = f"That's {x} your best"

Now the problem is if x is empty, there is an extra space in y, namely, y = "That's your best" rather than "That's your best". Does string interpolation auto add an space?


Solution

  • To your question:

    Does string interpolation auto add an space?

    No. You 're simply missing one space at the end of your first template string, and have one space too many in your second one. Use:

    x = f"{diff} short of " if diff > 0 else ""
    

    And:

    y = f"That's {x}your best"
    

    Now the trailing space after x will only be added if x is not empty.