-1

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?

dragonfly02
  • 3,403
  • 32
  • 55
  • You've tried to cram two different Python expressions into one replacement. It's unclear to me what your expected output is if diff *is* equal to zero, but you probably want either two separate replacements or a nested f-string (at which point I'd argue there are more readable ways to write it). – jonrsharpe Feb 10 '19 at 09:06
  • x = str(diff) + " short of" if diff > 0 else "" – Johnny Feb 10 '19 at 09:07
  • @Johnny the string needs to contain 'diff' in it e.g. if diff = 10, then it should be "10 short of" – dragonfly02 Feb 10 '19 at 09:08
  • @jonrsharpe if diff = 0 then diff > 0 is False so x is an empty string. – dragonfly02 Feb 10 '19 at 09:10
  • 1
    Then move the conditional *outside* the string: `f"{diff} short of" if diff > 0 else ""`. Your current f-string doesn't make sense. – jonrsharpe Feb 10 '19 at 09:10
  • Is this your expected code? `x = f"{diff} {'short of' if diff > 0 else ''}"` – Sabesh Feb 10 '19 at 09:16
  • 1
    @Sabesh I believe they want the whole expression to evaluate to `""` if `diff <= 0`. So no. – Bakuriu Feb 10 '19 at 09:18
  • I see that tanvir002700 had the correct solution by what you describe: `f"{str(diff) + 'short of' if diff > 0 else ''}"`. This is the only way in which your `f`-literal can end up evaluting to the empty string but, as you can check it makes the `f` literal useless... So the answer to your question would be you cannot using a sensible `f`-literal. You can using an `f`-literal made up of a single format placeholder which renders the `f`-literal useless – Bakuriu Feb 10 '19 at 09:22

1 Answers1

1

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.

Mig82
  • 4,856
  • 4
  • 40
  • 63