I would like to check if a list only contains either empty elements or whitespace, something like:
l = ['',' ','\n']
if all(whitespace or empty for element in l):
return True
Anyone know how to do this?
答案 0 :(得分:5)
Well your whitespace is simply str.isspace(..)
so:
if all('' == s or s.isspace() for s in l):
return True
答案 1 :(得分:2)
The easiest way is probably to use str.strip()
, which will return the empty string if the source string contains only whitespace. The empty string is falsey.
if not any(s.strip() for s in l): return True
答案 2 :(得分:1)
Try this:
if not any(s.strip() for s in l):
return True
答案 3 :(得分:1)
Slightly different answer using all instead of any:
if all([not x.strip() for x in l]):
return True
答案 4 :(得分:0)
另一种获得所需结果的方法,但使用str.split():
if all(not x.split() for x in l):
return True