【问题标题】:python: how to print separate lines from a list?python:如何从列表中打印单独的行?
【发布时间】:2018-12-22 09:31:12
【问题描述】:

这是我的代码:

class Message:

    def __init__(self,sender,recipient):
        self.sender = sender
        self.recipient = recipient
        self.wishList = []

    def append(self,line):
        self.wishList.append(str(line))
        for i in line:
            return i

    def toString(self):
        return 'From:{}\nTo:{}\n{}'.format(self.sender,self.recipient,
                                           self.wishList)

输出是:

From:Aria

To:Santa

['For Christmas, I would like:', 'Video games', 'World peace']

我怎样才能将行分开并输出如下?

From:Aria

To:Santa

For Christmas, I would like:

Video games

World peace

【问题讨论】:

  • 查看文档中的join'\n'.join(lst) 将为您提供一个由lst 中的所有字符串组成的字符串,它们之间带有换行符。
  • '\n'.join(['For Christmas, I would like:', 'Video games', 'World peace']) 将这些愿望打印在三行上。

标签: python python-3.x class append


【解决方案1】:

您可以通过"joinerchar".join(list) 将列表转换为字符串。在你的代码中它会是这样的。

return 'From:{}\nTo:{}\n{}'.format(self.sender,self.recipient,
                                       "\n".join(self.wishList))

【讨论】:

    【解决方案2】:

    假设你的数组是arr

    然后执行"\n".join(arr),它基本上采用数组并在每个数组之间插入新行。

    通过该示例,您应该能够弄清楚 :) 如果您需要更多帮助,请发表评论。

    【讨论】:

      【解决方案3】:

      首先,一些观察:

      1. 为什么在向愿望列表添加元素后返回第一个字符? (我认为它没用,所以我把它从我的答案中删除了)

      2. 我认为您应该添加圣诞节,我想:作为您要打印的模板的一部分。

      3. 使用str.join() 可能是连接wishList 元素的最佳选择。

      4. 你听说过PEP-8吗,基本上看起来你来自Java或C#,因为你使用upperCamelCase,在Python中_是首选。

      5. 假设您要输入一个字符串,我认为将行转换为str 是不相关的,但让我们保留它。

      假设你使用的是 Python 3.6+,你可以使用字符串插值:

      class Message:
          def __init__(self, sender, recipient):
              self.sender = sender
              self.recipient = recipient
              self.wish_list = []
      
          def append(self, line):
              self.wish_list.append(str(line))
      
          def toString(self):
              nl = '\n'
              return f'From: {self.sender}{nl}To: {self.recipient}{nl}For Christmas, I would like:{nl}{nl.join(self.wish_list)}'
      

      如果你运行以下代码:

      m = Message('Aria', 'Santa')
      m.append('Video games')
      m.append('World peace')
      print(m.toString())
      

      输出将是:

      From: Aria
      To: Santa
      For Christmas, I would like:
      Video games
      World peace
      

      【讨论】:

      • @AriaBB,如果可行,您介意验证这个答案吗?
      猜你喜欢
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 2023-01-03
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 2019-09-01
      • 2023-04-03
      相关资源
      最近更新 更多