删除python中多余的空格
我有一个文件,上面写着:删除python中多余的空格,python,string,Python,String,我有一个文件,上面写着: o hi! My name is Saurabh. o I like python. 我想要像这样的东西: o hi! My name is Saurabh. o I like python. 我试着说: removedSpaces=' '.join(lineWithSpaces.split()) 看起来它删除了所有的空格 它给了我 o hi! My name is Saurabh.o I like python. 这是不正确的。无论如何,是否有可能
o hi! My name is Saurabh.
o I like python.
我想要像这样的东西:
o hi! My name is Saurabh.
o I like python.
我试着说:
removedSpaces=' '.join(lineWithSpaces.split())
看起来它删除了所有的空格
它给了我
o hi! My name is Saurabh.o I like python.
这是不正确的。无论如何,是否有可能实现上述输出
import re
removedSpaces = re.sub(r'\n{3,}', "\n\n", lineWithSpaces)
这会将三个或更多新行的所有运行转换为两个新行 不完全正确;这将用两条换行符替换所有空格。您想要拆分('\n')@nneonneo,Santa:不。没有修复。现在字符串中的每一个换行符都将替换为两个换行符:
'\n\n.join(“a\n\nb.split(“\n”))
给出'a\n\n\nb'
。它在处理数字和\n之后工作。非常感谢--索拉布
'\n\n'.join(linesWithSpaces.split('\n'))
while "\n\n" in lineWithSpaces:
lineWithSpaces = lineWithSpaces.replace("\n\n", "\n")