首页 > 解决方案 > 如何删除每行中的多个空格并替换为单个空格?

问题描述

我是脚本新手,我试图删除一行中的多个空格并将其替换为一个空格。

输入.txt

Hello     world
Welcome     to     python

输出应该像

Hello world
Welcome to python

我按照以下命令

with open ('input.txt', 'r') as i_f, open ('output.txt', 'w') as o_f:
    for line in i_f:
        o_f.write(re.sub('\s+',' ', line))

我的输出类似于

Hello world Welcome to python

我正在尝试用每行的一个空格替换多个空格。我不想将多行合并为一行。谁能帮我删除多个空格并通过不加入行来用单个空格替换它们。任何帮助,将不胜感激。提前致谢。

标签: pythonpython-3.xregex

解决方案


您的问题是由匹配任何空白字符的事实引起的\s,并且每行末尾的换行符都算作空白。

由于 Python 中没有除换行符之外的空白字符的简写字符,因此您需要明确列出要匹配的空白字符:

with open ('input.txt', 'r') as i_f, open ('output.txt', 'w') as o_f:
    for line in i_f:
        # Match only tabs and spaces
        o_f.write(re.sub('[\t ]+',' ', line))

如果您要使用正则表达式,我强烈推荐本教程。太棒了。


推荐阅读