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', '♣'))))