修剪多行的空白

Roc*_*Lee 2 python

我尝试使用s.strip()这样修改python中的空格,但它只在第一行上工作:

输入:

   a
    b
Run Code Online (Sandbox Code Playgroud)

输出:

a
    b
Run Code Online (Sandbox Code Playgroud)

如何从多行修剪空白?这是我的代码:

码:

import sys

if __name__ == "__main__":
    text_file = open("input.txt", "r")
    s = text_file.read()
    s = s.strip()
    text_file.close()
    with open("Output.txt", "w") as text_file:
        text_file.write(s)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 10

拆分线条,剥离每条线条,然后重新加入:

s = text_file.read()
s = '\n'.join([line.strip() for line in s.splitlines()])
Run Code Online (Sandbox Code Playgroud)

这将使用该str.splitlines()方法以及str.join()方法将行重新组合在一起,并在其间添加换行符.

更好的是,逐行读取文件,一次性处理和写出; 这样你整个过程就需要更少的内存:

with open("input.txt", "r") as infile, open("Output.txt", "w") as outfile:
    for line in infile:
        outfile.write(line.strip() + '\n')
Run Code Online (Sandbox Code Playgroud)


Ana*_*mar 3

出现此问题的原因是string.strip()仅删除尾随和前导空格,而不会删除中间的空格。

对于输入 -

   a
    b
Run Code Online (Sandbox Code Playgroud)

并在做text_file.read()

实际的字符串表示形式是 -

'   a\n    b'
Run Code Online (Sandbox Code Playgroud)

s.strip()会去除尾随和前导的空格,但不会\n去除中间的 和 空格,因此您会得到多行,并且中间的空格不会被删除。

为了使您的案例正常工作,您应该逐行读取输入,然后剥离每一行并将其写回。

例子 -

import sys

if __name__ == "__main__":
    with open("input.txt", "r") as text_file, open("Output.txt", "w") as out_file:
        for line in text_file:
            out_file.write(line.strip() + '\n')
Run Code Online (Sandbox Code Playgroud)