Skip to content Skip to sidebar Skip to footer

How Do I Remove Blank Lines From A String In Python?

Lets say I have a variable that's data contained blank lines how would I remove them without making every thong one long line? How would I turn this: 1 2 3 Into this: 1 2 3 Wit

Solution 1:

import os
text = os.linesep.join([s for s intext.splitlines() if s])

Solution 2:

You can simply do this by using replace() like data.replace('\n\n', '\n')

Refer this example for better understanding.!!

data = '1\n\n2\n\n3\n\n'
print(data)

data = data.replace('\n\n', '\n')
print(data)

Output

1

2

3


1
2
3

Solution 3:

text = text.replace(r"\n{2,}","\n")

Post a Comment for "How Do I Remove Blank Lines From A String In Python?"