Saurabh Ghorpade
Saurabh Ghorpade

Reputation: 1157

removing extra blank spaces in python

I have a file which reads:

o hi! My name is Saurabh.




o I like python.

I want something like:

o hi! My name is Saurabh.

o I like python.

I tried the line:

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

Looks like it removes all the spaces

It gives me

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

Which is incorrect. Is it possible to achieve the above output by anyway.

Upvotes: 0

Views: 588

Answers (3)

martiangoblin
martiangoblin

Reputation: 109

while "\n\n" in lineWithSpaces:
    lineWithSpaces = lineWithSpaces.replace("\n\n", "\n")

Upvotes: 0

Santa
Santa

Reputation: 11545

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

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336498

import re
removedSpaces = re.sub(r'\n{3,}', "\n\n", lineWithSpaces)

This converts all runs of three and more newlines to two newlines.

Upvotes: 1

Related Questions