4

I'm working in Python 3.x, and I'm trying to get an f-string to report from a __repr__ function, but I can't seem to get the following formatted string to work the way I'm expecting it to.

I'm constantly getting "SyntaxError: unexpected EOF while parsing"

def __repr__(self):
    return f"Player has {'Soft' if self.soft > 0} {self.count}. Cards are {self.cards}."

The part that gives the error is {'Soft' if self.soft > 0}. And if it's not clear, I'm trying to include the word "Soft" IFF self.soft>0, if not, don't add any word to the string.

Jongware
  • 22,200
  • 8
  • 54
  • 100
GrantG
  • 43
  • 3
  • To be fair, that error message is quite misleading. The parser hasn't reached the end of the file (in any practical sense), but the end of the `{...}` block inside the f-string. – chepner Nov 28 '18 at 14:16
  • Also, see https://stackoverflow.com/questions/1984162/purpose-of-pythons-repr for the kinds of strings that `__repr__` and `__str__` should return. – chepner Nov 28 '18 at 14:18

1 Answers1

5

Unlike the if statement, the else keyword in the conditional expression is not optional:

def __repr__(self):
    return f"Player has {'Soft' if self.soft > 0 else ''} {self.count}. Cards are {self.cards}."
chepner
  • 497,756
  • 71
  • 530
  • 681
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Awesome. Thank you. – GrantG Nov 28 '18 at 16:12
  • Follow up question, what did you mean by the "if" is optional? – GrantG Nov 28 '18 at 16:13
  • Glad to be of help. I meant that in an `if` statement, the `else` block is optional, but in a conditional expression, even though it also uses the `if` keyword, the `else` portion of the expression is not optional. Was assuming that you omitted the `else` keyword simply because you drew parallel from the usage of the `if` statement. – blhsing Nov 28 '18 at 16:20