0

(Sorry if the question is somewhat vague, I'm not sure of a better title)

I'm not sure what it's called when you get something similar to the following:

[<main.Card object at 0x00350490>, <main.Card object at 0x00350590>] [<main.Card object at 0x00350510>, <main.Card object at 0x003501B0>]

but I'm trying to print out the more readable format. I want to make sure things are in the correct order before I go more into changing the order.

import random as rd


class Card:
    card_rank = [str(n) for n in range(2, 10)]
    card_rank.extend(['Ten', 'Jack', 'Queen', 'King', 'Ace'])
    card_suit = ['Spades', 'Clubs', 'Diamonds', 'Hearts']

    def __init__(self, rank, suit):
        assert 2 <= rank <= 14 and 1 <= suit <= 4
        self.rank = rank
        self.suit = suit

    def __str__(self):
        return '{} of {}'.format(Card.card_rank[self.rank - 2], Card.card_suit[self.suit - 1])


class Deck:
    def __init__(self):
        self.cards = [Card(rank, suit) for rank in range(2, 14 + 1) for suit in range(1, 4 + 1)]


class Player:
    def __init__(self):
        self.hand = []

    def build_hand(self, card):
        self.hand.append(card)

    def __str__(self):
        return self.hand


class Dealer(Deck, Player):

    def deck_shuffle(self):
        rd.shuffle(self.cards)

    def deck_deal(self):
        single_card = self.cards.pop()
        print(single_card)
        return single_card


dealer = Dealer()
player_hand = Player()
dealer_hand = Player()


dealer.deck_shuffle()


player_hand.build_hand(dealer.deck_deal())
dealer_hand.build_hand(dealer.deck_deal())
player_hand.build_hand(dealer.deck_deal())
dealer_hand.build_hand(dealer.deck_deal())

print(player_hand.hand)
print(dealer_hand.hand)

I am pretty sure this is a very obvious thing that I should be able to realize on my own, but the trial and error has only resulted in error. What is it that I'm doing that creates the unreadable format and why doesn't str() or str work here?

Luck Box
  • 90
  • 1
  • 13
  • Your cards are inside a list. When printing a list `repr()` will be called on the items, not `str()`. – Klaus D. May 04 '19 at 00:48

1 Answers1

1

The __str__ method for lists doesn't recursively call str on the elements in the list; it just uses the __repr__. If you want a better display of a hand, generate it yourself:

print(" ".join([str(c) for c in player_hand.hand))
print(" ".join([str(c) for c in dealer_hand.hand))
chepner
  • 497,756
  • 71
  • 530
  • 681
  • `print(*player_hand.hand)` – TigerhawkT3 May 04 '19 at 00:56
  • True, though that gives you less control over the final appearance. I probably should have used something like `print(", ".join(...))` as the example. (And yes, `print` has a `sep` argument. Maybe there is no difference without resorting to a custom `Hand` class with its own `__str__` method :) ) – chepner May 04 '19 at 12:32