我怎样才能摆脱双空格? (Python)

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

我有一个数据文件(.txt)包含一些行,每行如下:

0 45 1 31 2 54 3 54 4 64

零前有一个白色的space,每两个整数之间有两个space,最后有一个白色的space。我想要的是像下面这样:

0 45 1 31 2 54 3 54 4 64

我正在尝试所有方法(使用 Python)但我没有成功!

当然最后我想改成:

45 31 54 54 64

也就是消除数字 0 到 4。但是如果我到达第一步,最后一步可能更容易做到。

例如我试过这个:

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

但是在 `myfile_2' 中,字符串还没有更正。

相应地进行了更改:

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

编辑 1:按照评论中的建议添加了 strip()
编辑 2:进行了更改。

您可以使用 re 代替:

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

您可以使用 regular expression 来匹配一个或多个 space(' +',其中 + 表示 "one or more")并将它们替换为单身 space:

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