在python中删除多余的空格

2024-09-20 04:11:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,上面写着:

o hi! My name is Saurabh.




o I like python.

我想要这样的东西:

^{pr2}$

我试过这句话:

removedSpaces=' '.join(lineWithSpaces.split())

看起来它把所有的空格都去掉了

它给了我

o hi! My name is Saurabh.o I like python. 

这是不正确的。是否有可能通过任何方式实现上述输出。在


Tags: 文件nameismy方式hilikesplit
3条回答
while "\n\n" in lineWithSpaces:
    lineWithSpaces = lineWithSpaces.replace("\n\n", "\n")
import re
removedSpaces = re.sub(r'\n{3,}', "\n\n", lineWithSpaces)

这会将三个或更多新行的所有运行转换为两个新行。在

'\n\n'.join(linesWithSpaces.split('\n'))

相关问题 更多 >