Search code examples
pythonstringeofreprf-string

EOF Error while using f-string in __repr__() function


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.


Solution

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