3

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

Without turning it into this:

123
Markus
  • 301
  • 1
  • 4
  • 12

3 Answers3

4
import os
text = os.linesep.join([s for s in text.splitlines() if s])
Lojas
  • 195
  • 3
  • 13
3

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
Sreeram TP
  • 10,221
  • 6
  • 43
  • 92
-1
text = text.replace(r"\n{2,}","\n")
celsowm
  • 556
  • 8
  • 30
  • 54