Reputation: 338
x=["x1",""," "," ","y1"]
y=[]
import re
for id in range(0,5):
if(not re.findall("^\s*$",x[id])): y.append(x[id])
y
["x1","y1"]
I can delete blank string in a list in python,it feels complicated,how can i simplify my code?
Upvotes: 0
Views: 88
Reputation: 416
y = filter(lambda i: i.strip(), x)
#['x1', 'y1']
or more succinct version by @Jiri
filter(str.strip, x)
Upvotes: 2
Reputation: 239433
You can either use list comprehension based filtering, like this
print [current_string for current_string in x if current_string.strip() != ""]
# ['x1', 'y1']
In Python, an empty string is considered as Falsy. So, the same can be written succinctly like this
print [current_string for current_string in x if current_string.strip()]
Apart from that, you can use the filter
function, to filter out the empty strings like this
stripper, x = str.strip, ["x1",""," "," ","y1"]
print filter(stripper, x)
Upvotes: 0
Reputation: 37846
>>> o = ['','1']
>>> n = []
>>> for each in o:
if each.strip():
n.append(each)
>>> n
['1']
>>>
Upvotes: 0
Reputation: 33997
list comprehension with if statement:
y = [i for i in x if i.strip()]
#['x1', 'y1']
Upvotes: 2