Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing empty items from a list (Python)

I'm reading a file in Python that isn't well formatted, values are separated by multiple spaces and some tabs too so the lists returned has a lot of empty items, how do I remove/avoid those?

This is my current code:

import re

f = open('myfile.txt','r') 

for line in f.readlines(): 
    if re.search(r'\bDeposit', line):
        print line.split(' ')

f.close()

Thanks

like image 492
eozzy Avatar asked Sep 23 '26 07:09

eozzy


1 Answers

Don't explicitly specify ' ' as the delimiter. line.split() will split on all whitespace. It's equivalent to using re.split:

>>> line = '  a b   c \n\tg  '
>>> line.split()
['a', 'b', 'c', 'g']
>>> import re
>>> re.split('\s+', line)
['', 'a', 'b', 'c', 'g', '']
>>> re.split('\s+', line.strip())
['a', 'b', 'c', 'g']
like image 95
Max Shawabkeh Avatar answered Sep 25 '26 20:09

Max Shawabkeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!