【问题标题】:Removing blank lines between output lines删除输出行之间的空白行
【发布时间】:2019-08-05 14:46:07
【问题描述】:

我正在尝试格式化文档。无论是否有信息,每行都需要 158 个空格。我得到了我需要的正确输出,但它在两者之间打印了额外的行。

示例:我应该期待看到,

1
2
3
4

相反,我得到:

1

2

3

4

我尝试了 rstrip() 并删除了额外的空白行,但也删除了我需要格式化的空格。

   for line in f1:

    #removes leading white spaces
        line.strip()
    #finds the length of the line
        x = (len(line))
    #hard set value for the type of document
        y = 158
    #finding the difference between string length and hard value
        z = (y - x)
    #prints the difference and string length
        Str1 = line.ljust(z)
        print (Str1)

我希望每行的长度正好为 158 个字符,并且每行之间的空格为零。目前我可以得到空格或 158 个字符行,不能同时得到。

【问题讨论】:

  • 你试过line = line.strip()吗? strip() 函数不是就地操作,但它确实消除了字符串上可能已经存在的换行符。
  • 你可以打印 '\b' 甚至可以在 print 语句中尝试 end=""

标签: python python-3.x


【解决方案1】:
for line in f1:

#removes leading white spaces
    line.strip()
#finds the length of the line
    x = (len(line))
#hard set value for the type of document
    y = 158
#finding the difference between string length and hard value
    z = (y - x)
#prints the difference and string length
    Str1 = line.ljust(z)
    print (Str1,end="")

end="" 不会再创建一个 "\n" 并且您的输出会很好。

【讨论】:

    【解决方案2】:

    你可以试试:

    line.replace("\n\n", "\n")
    

    【讨论】: