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
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With