【问题标题】:how to return a string in a specific format in classes?如何在类中以特定格式返回字符串?
【发布时间】:2013-12-03 01:59:30
【问题描述】:

假设我有一类书籍,我已经定义了 init。我希望我的 str 以这种格式返回书籍:

'Book("Dr.!Seuss",!"The!Cat!in!the!Hat",!"12345")'

我有这个:

def __str__(self):
   return 'Books( title={0}'.format(self.title)

我还没有检查它是否有效。这是另一个问题。我如何检查它是否像我如何创建包含书籍的东西一样工作?

【问题讨论】:

  • 当你说“包含书籍的东西”时,你的意思是像数组这样的东西吗?为什么你不能用一本书来测试它来验证你的方法是正确的?
  • @ATG 什么是数组?

标签: function class python-3.x


【解决方案1】:

做这样的事情:

li=['Dr.','Seuss','The','Cat','in','the','Hat','12345']
print('Book({})'.format('!'.join(li)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    • 2018-01-03
    • 2012-12-26
    相关资源
    最近更新 更多