0

So say i had some text like this:

line num 1
line num 2

line num 3



line num 4

I am trying to get rid of all the new lines in between line 2 and 3 and line 3 and 4 while having all of the line num on separate new lines. How would i accomplish this? I have already tried puth=ing them into a list then looping throught them and taking out all of the lone '\n'

ex:

obj=['line num 1','line num 2','\n','line num 3','\n','\n','line num4']
a=-1
for i in obj:
    a+=1
    if i=='\n':
        print 'yes'
        del obj[a]


print obj

output:

['line num 1', 'line num 2', 'line num 3', '\n', 'line num4']

It catches some but not all.

P'sao
  • 2,946
  • 11
  • 39
  • 48

5 Answers5

4

In short: don't erase elements while iterating over a list.

Here you will find lot of ways to do this: Remove items from a list while iterating

Note: this is probably the shortest and most pythonic:

filter(lambda x: x!='\n', obj)
Community
  • 1
  • 1
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
1

I'd simply use regex on the whole file content:

>>> s = """line num 1
line num 2

line num 3



line num 4"""
>>> import re
>>> print re.sub('\n+', '\n', s)
line num 1
line num 2
line num 3
line num 4

P.S. You should newer change list while iterating it.

Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75
1

Maybe if not item.isspace() gives you something more readable:

>>> obj = ['line num 1', 'line num 2', '\n', 'line num 3', '\n', '\n', 'line num4']

>>> [item for item in obj if not item.isspace()]

['line num 1', 'line num 2', 'line num 3', 'line num4']
>>> 
joaquin
  • 82,968
  • 29
  • 138
  • 152
0
def remove_new_line(obj):
    if "\n" in obj:
        obj.remove("\n")
    remove_new_line(obj)
    return obj

obj = ['line num 1', 'line num 2', '\n', 'line num 3', '\n', '\n', 'line num4']

print remove_new_line(obj)
Asterisk
  • 3,534
  • 2
  • 34
  • 53
0

You can also try this:

f = open("your file.txt",'r')
values = f.read()
val = re.split(r"\n+",values)
print val

output = ['line num 1', 'line num 2', 'line num 3', 'line num 4']

RanRag
  • 48,359
  • 38
  • 114
  • 167