3zz*_*zzy 2 python regex split list
我正在读取一个格式不正确的Python文件,值由多个空格和一些标签分隔,所以返回的列表有很多空项,如何删除/避免这些?
这是我目前的代码:
import re
f = open('myfile.txt','r')
for line in f.readlines():
if re.search(r'\bDeposit', line):
print line.split(' ')
f.close()
Run Code Online (Sandbox Code Playgroud)
谢谢
Max*_*keh 11
不要明确指定' '为分隔符.line.split()将在所有空格上分开.它相当于使用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']
Run Code Online (Sandbox Code Playgroud)