Reputation: 389
In the task, I am trying to create an object of a deck of cards. The output is something like ['A of Hearts', 'A of Diamonds', 'A of Clubs', ...] and what I want is to convert the output to a list and get the length of the list.
After I created an instance from the class, I tried to get the type of the output, and it returns <class '__main__.Card'>
.
I tried to convert the output, which should be a string, into a list by:
Split the output string
directly use list() function
class Card:
def __init__(self):
self.suit = ["Hearts","Diamonds","Clubs","Spades"]
self.value = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
self.cards = []
for x in self.value:
y = x + " of"
for z in self.suit :
aa = y + " " + z
self.cards.append(aa)
def __repr__(self):
return str(self.cards)
cards1 = Card()
When I use the first function, it returns error 'Card' object has no attribute 'split'
When I use the second function, it returns error 'Card' object is not iterable
In this case what should I do? Many thanks
Upvotes: 1
Views: 381
Reputation: 448
The structure of the class is not fine, but it works. You are returning an object, this object should have a method to return the string/list or you have to directly get the list as follow.
str1 = ''.join(cards1.cards)
Upvotes: 1
Reputation: 360
If you are trying to just get the output in string form, then use an f
string or a formatted string:
str1 = f"test1: {cards1}"
str2 = "test2: {}".format(cards1)
Upvotes: 1