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
  • 331
  • 2
  • 4
  • 13

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
  • 11,346
  • 7
  • 54
  • 108
-1
text = text.replace(r"\n{2,}","\n")
celsowm
  • 846
  • 9
  • 34
  • 59