【问题标题】:Removing whitespace from the end in python [duplicate]在python中从末尾删除空格[重复]
【发布时间】:2020-08-21 05:58:33
【问题描述】:

在输出结束后我得到了额外的空白,因为我使用了end=' '。我该如何解决这个问题?

for i in range(0,6):
    for g,h in q[i].items():
        print(h/len(q1[i]), end=" ") //here
    print()

【问题讨论】:

  • 少迭代一个,为最后一个单独打印语句
  • 从末尾删除空格。试试看:end=''
  • 试试str.strip()。它会删除尾随空格。
  • @HarshaBiyani 但是这不会同时从其他输出中删除空格吗?我只是不想要最后的空格
  • @Kettle3D 逗号分隔字典的元组对,即键、值

标签: python python-3.x


【解决方案1】:

每行只有一个打印语句怎么样?您可以使用join 在值之间放置空格。

for i in range(6):
    print(' '.join(str(h/len(q1[i])) for h in q[i].values()))

【讨论】:

    【解决方案2】:
    for i in range(0,6):
        print(*[h/len(q1[i]) for g,h in q[i].items()])
        print()
    

    使用this answer,我们可以简单地解压缩列表以打印所有内容,而无需内部for 循环。

    例子:

    >>> print(*[1,2,3])
    1 2 3
    

    【讨论】:

      【解决方案3】:

      使用 str.join() 在项目之间添加空格:

      for i in range(0,6):
          items = [str(h/len(q1[i])) for g,h in q[i].items()]
          print(" ".join(items))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多