praveen
praveen

Reputation: 21

Replace continuous occurrence of "\n" with a single "\n" in python

I have a text file that contains multiple blank lines and I want to remove those blank lines. The only solution I can come up with is to remove the occurrence of "\n"s with a single "\n". I know this can be done using a regular expression but don't know how to do it in python. I googled a lot and it didn't work.

Upvotes: 0

Views: 1804

Answers (1)

khelwood
khelwood

Reputation: 59096

import re
txt = re.sub('\n+','\n',txt)

Substitute any sequence of 1 or more new-lines with a single new-line.

Upvotes: 5

Related Questions