How to remove multiple spaces in every line and replace with single space?

Viewed 1778

I am new to scripting and trying to remove multiple spaces in a line and replace it with a single space.

input.txt

Hello     world
Welcome     to     python

the output should be like

Hello world
Welcome to python

I followed the below command

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))

My output is something like

Hello world Welcome to python

I am trying to substitute multiple spaces with a single space of every line. I do not want to join the multiple lines into a single line. Can anyone please help me to delete multiple spaces and replace them with a single space by not joining the lines. Any help would be appreciated. Thanks in advance.

3 Answers

Add a newline character to the end of every line you write.

Or you could change your regular expression to only match spaces (as opposed to any whitespace character) or whatever subset of whitespace characters you want to consolidate.

Your problem is caused by the fact that \s matches any whitespace character, and the newline character at the end of each line counts as whitespace.

Since there's no shorthand character in Python for whitespace characters excluding newlines, you need to explicitly list out which whitespace characters you want to match:

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))

If you're going to be working with regular expressions, I strongly recommend this tutorial. It is fantastic.

You can replace matches of the regular expression

r' (?= |$)'

with an empty string.

Start your engine!

I have assumed any spaces at end of the string are to be removed as well. If spaces at the end of the string are to be replaced with a single space, use:

r' (?= )'

or replace matches of

r' +'

with a space.

Related