Я пытаюсь написать код для устранения ненужных пробелов в документе - PullRequest
0 голосов
/ 25 июня 2019

Я удаляю пробелы из текста, используя python

test_text="Python is the                    best"
test_text=test_text.split(" ")
list(test_text)
print(test_text)
for i in test_text:
    if i == " ":
        test_text.remove(i)
print(test_text) 

ожидаемый результат = ("python", "is", "the", "best") или "python is the best"

1 Ответ

1 голос
/ 25 июня 2019

Вы можете использовать re модуль:

import re

test_text="Python is the                    best"

output = re.sub(r'(\s){2,}', r'\1', test_text)
print(output)

Печать:

Python is the best

Редактировать (без повторного модуля):

test_text="Python is the                    best"
print(test_text.split())

Печать:

['Python', 'is', 'the', 'best']

Редактировать 2:

#to join it to one string:
print(' '.join(test_text.split()))

Печать:

Python is the best
...