python - 将从类创建的字符串对象转换为列表

标签 python

在任务中,我试图创建一副纸牌的对象。输出类似于 ['A of Hearts', 'A of Diamonds', 'A of Clubs', ...],我想要的是将输出转换为列表并获取列表的长度。

从类创建实例后,我尝试获取输出的类型,它返回 <class '__main__.Card'>

我尝试将输出(应该是字符串)转换为列表:

  1. 分割输出字符串

  2. 直接使用list()函数

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()

当我使用第一个函数时,它返回错误 “Card”对象没有属性“split”

当我使用第二个函数时,它返回错误“Card”对象不可迭代

这种情况我该怎么办? 非常感谢

最佳答案

如果您只想获取字符串形式的输出,请使用 f 字符串或格式化字符串:

str1 = f"test1: {cards1}"
str2 = "test2: {}".format(cards1)

关于python - 将从类创建的字符串对象转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57047542/

相关文章:

python - 如何在 python 中将集合转换为整数?

python - 如何从 http ://shinytoylabs. com/jargon/using python 抓取文本

Python 正则表达式 findall() 返回不需要的子字符串(包括正确答案)

python - 使用 re 模块过滤

python - South django 表已经存在

python - 使用用户输入作为正则表达式搜索表达式

python - python 中 not() 的顺序有什么问题?

python - 按月绘制 groupby 数据

python - 在SQL中插入时如何刷新django连接

python - 具有可变和不可变属性的数据类样式对象?