3

I was implementing my own format specifiers by overriding the __format__() method in my class. Now the trouble that I am having is that I am getting the below error. Is it because I can not use %s for any other format specification other than str() or am I doing something wrong here.

Traceback (most recent call last): File "test.py", line 66, in print("Dealer has {0:%r of %s}".format(NumberCard(1, Club))) File "ch1.py", line 24, in format result = format_spec.replace("%r", self.rank).replace("%s", self.suit) TypeError: replace() argument 2 must be str, not int

class Card:

    insure = False

    def __init__(self, rank, suit):
        self.suit = suit
        self.rank = rank
        self.hard, self.soft = self._points()

    def __str__(self):
        return "{rank}{suit}".format(**self.__dict__)

    def __repr__(self):
        return "{__class__.__name__}(suit={suit!r}, rank={rank!r})".format(__class__=self.__class__, **self.__dict__)

    def __format__(self, format_spec):
        if format_spec == "":
            return str(self)
        else:
            result = format_spec.replace("%r", self.rank).replace("%s", self.suit)
            result = result.replace("%%", "%")
            return result

class NumberCard(Card):

    def _points(self):
        return int(self.rank), int(self.rank)


class Suit:

    def __init__(self, name, symbol):
        self.name = name
        self.symbol = symbol

I am passing my arguments as

print("Dealer has {0:%r of %s}".format(NumberCard(1, Suit('Club', '♣'))))

0

2 Answers 2

2
NumberCard(1, Suit('Club', '♣'))

So, the rank is an int

You're calling replace("%r", self.rank)

The error says replace() argument 2 must be str, not int

Use str(self.rank) in the replace instead

Sign up to request clarification or add additional context in comments.

Comments

1

Convert it?

def __format__(self, format_spec):
    if format_spec == "":
        return str(self)
    else:
        result = format_spec.replace("%r", str(self.rank)) # stringify your int
        result = result.replace("%s", str(self.suit.symbol)) # symbol instead class name
        result = result.replace("%%", "%")

Replace works on replace(str,str) - you can not replace a str with a int using it.

Doku: https://docs.python.org/3.6/library/stdtypes.html#str.replace

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.