【问题标题】:Avoiding trailing newline in Python [duplicate]避免在 Python 中使用尾随换行符 [重复]
【发布时间】:2019-05-06 04:16:57
【问题描述】:

我现在正在做一个项目,作为功能之一,我应该遍历一个列表并在不同的行中输出项目。

代码如下所示:

dictionary = {'key0': sorted([item + "\n" 
              for item in mylist}])

print(x[1]) for x in dictionary.items()

但是,这每次都会留下一个尾随换行符。

这样的东西有用吗?

string = ''

otherlist = sorted([item + "\n" for item in mylist])

for i in range(len(otherlist)):
    string.join(sorted[i])

string.rstrip()

print(string)

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python python-3.x newline


    【解决方案1】:

    使用str.join:

    print("".join(x[1] for x in dictionary.items()))
    

    【讨论】:

      【解决方案2】:

      不要在列表理解中添加换行符,只需使用换行符加入列表即可。

      lines = '\n'.join(otherlist)
      

      【讨论】:

      • 我不知道list.join 方法。也许你的意思是'\n'.join(otherlist)
      • @TrebledJ 你是对的,我已经有一段时间没有每天写python了;)
      猜你喜欢
      • 2012-07-01
      • 2017-04-21
      • 2011-12-21
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      相关资源
      最近更新 更多