Reputation: 562
I'm trying to get the string representation of my class correct. To do this I need to concatenate several lists into a string. The lists should be whitespace separated in the string.
These are my lists:
[['C', 'A'], ['C', '2'], ['C', '3'], ['C', '4'], ['C', '5'], ['C', '6'], ['C', '7'], ['C', '8'], ['C', '9'], ['C', 'T'], ['C', 'J'], ['C', 'Q'], ['C', 'K'], ['S', 'A'], ['S', '2'], ['S', '3'], ['S', '4'], ['S', '5'], ['S', '6'], ['S', '7'], ['S', '8'], ['S', '9'], ['S', 'T'], ['S', 'J'], ['S', 'Q'], ['S', 'K'], ['H', 'A'], ['H', '2'], ['H', '3'], ['H', '4'], ['H', '5'], ['H', '6'], ['H', '7'], ['H', '8'], ['H', '9'], ['H', 'T'], ['H', 'J'], ['H', 'Q'], ['H', 'K'], ['D', 'A'], ['D', '2'], ['D', '3'], ['D', '4'], ['D', '5'], ['D', '6'], ['D', '7'], ['D', '8'], ['D', '9'], ['D', 'T'], ['D', 'J'], ['D', 'Q'], ['D', 'K']]
This is the code I use to join them:
def __str__(self):
str_deck_cards = 'Deck contains '
for t in self.deck_cards:
str_deck_cards += ' '.join(t)
return str_deck_cards
However my output looks like this:
Deck contains C AC 2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KS AS 2S 3S 4S 5S 6S 7S 8S 9S TS JS QS KH AH 2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KD AD 2D 3D 4D 5D 6D 7D 8D 9D TD JD QD K
Why is it not joining the lists correctly?
I've also tried with set()
def __str__(self):
str_deck_cards = 'Deck contains '
for t in self.deck_cards:
str_deck_cards += ' '.join(set(t))
return str_deck_cards
But it still doesn't get it right. I'm out of ideas now, any suggestions?
Upvotes: 0
Views: 734
Reputation: 8709
Actually nothing is removed. You are placing a space between two characters in a sublist C AC 2
not between two sublists CA C2
. So replace :
str_deck_cards += ' '.join(set(t)) # gives C AC 2C 3C 4C 5...
by:
str_deck_cards +=''.join(t)+' ' # gives CA C2 C3 C4 C5...
This will fix the issue.
Upvotes: 1
Reputation: 2790
The .join
takes an iterable and adds the string you wanted BETWEEN the items. So this works as expected.
What you want is that when concatenating the strings generated, a whitespace is added so -
str_deck_cards += ' '.join(t) + ' '
of course, at the end, if necessary, you'll have to get rid of the trailing whitespace.
== Edit ==
you could also do something like that:
return 'Deck contains ' + ' '.join([' '.join(x) for x in self.deck_cards])
Upvotes: 3