我正在尝试编写代码以消除文档中不必要的空格

时间:2019-06-25 20:16:11

标签: python text-formatting

我正在使用python消除文本中的空格

rooms

expected result =(“ python”,“ is”,“ the”,“ best”)或“ python is best”

1 个答案:

答案 0 :(得分:1)

您可以使用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

编辑(不带re模块):

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