How can I get rid of double spaces? (Python)

Question:

I have a data file (.txt) containing some lines, each line as following:

0 45 1 31 2 54 3 54 4 64

With a white space before zero, two spaces between each two integers and a white space at the end. What I want is to have it like following:

0 45 1 31 2 54 3 54 4 64

I am trying everything (using Python) but I am not successful!

Of course at the end I want to reform it to:

45 31 54 54 64

That is eliminating the numbers 0 to 4 as well. But this last step is maybe easier to do if I reach the first one.

For example I have tried this:

with open('myfile', rt') as openfile, open('myfile_2, 'a') as csvfile:
    for line in openfile:
            A = str(line).replace('  ', ' ')
            Writer = csv.writer(csvfile, delimiter=' ', quotechar=' ')
            Writer.writerow([A])

But yet in the `myfile_2′ the string is not corrected.

Asked By: Mostafa

||

Answers:

Made Changes Accordingly:

with open('newtes.txt', 'w') as outfile, open('tes.txt', 'r') as infile:
    for line in infile:
        outfile.write(line.replace('  ',' ').strip())

edit 1 : strip() added as suggested in the comment
edit 2 : Made Changes.

Answered By: radix

You could use re instead:

import re
# Handles multiple whitespaces
WHITE_SPACE_PATTERN = re.compile(r' +')
# or
# WHITE_SPACE_PATTERN = re.compile(r's+')
# if you want to handle newlines as well

sample_string = "0  45  1  31  2  54  3  54  4  64"
cleaned_string = re.sub(WHITE_SPACE_PATTERN, ' ', sample_string.strip())
Answered By: fixatd

You could use a regular expression to match one or more spaces (' +', where + implies “one or more”) and substitute them with a single space:

import re
line = ''
file_object  = open("test.txt", "r+")
for line in file_object:
    line=line
print re.sub(' +', ' ',line.lstrip())
Answered By: krishna krish

For any number of extra spaces I would use:

line = ' '.join(line.split(' '))

or:

line = ' '.join(line.split())

for all whitespace chars (‘ tnrx0bx0c’)

Answered By: Leonid Selivanov
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.