我想测试一个句子是否包含除空白字符以外的任何内容。这就是我目前使用的:
if len(teststring.split()) > 0:
# contains something else than white space
else:
# only white space
这够好吗?有没有更好的方法呢?
答案 0 :(得分:13)
字符串有一个名为str.isspace
的方法,根据文档:
如果字符串中只有空格字符并且至少有一个字符,则返回[s] true,否则返回false。
所以,这意味着:
if teststring.isspace():
# contains only whitespace
会做你想做的事。
答案 1 :(得分:7)
为此,我会使用strip()函数。
if teststring.strip():
# non blank line
else:
# blank line
答案 2 :(得分:2)
你可以使用.strip()。
如果只有空格,结果字符串将为空。
if teststring.strip():
# has something other than whitespace.
else:
# only whitespace
或许更明确的是,JBernardo指出:
if not teststring.isspace():
# has something other than whitespace
else:
# only whitespace.
答案 3 :(得分:1)
if teststring.split():
print "not only whitespace!"
else:
print ":("