4

我想测试一个句子是否包含除空白字符之外的任何其他内容。这是我目前使用的:

if len(teststring.split()) > 0:
    # contains something else than white space
else:
   # only white space

这够好吗?有没有更好的方法呢?

4

4 回答 4

14

str.isspace根据文档,字符串有一个称为该方法的方法:

如果字符串中只有空白字符并且至少有一个字符,则返回 [s] true,否则返回 false。

所以,这意味着:

if teststring.isspace():
    # contains only whitespace

会做你想做的。

于 2012-06-21T01:43:58.020 回答
7

为此,我将使用strip()函数。

  if teststring.strip():
      # non blank line
  else:
      # blank line
于 2012-06-21T01:42:02.783 回答
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.
于 2012-06-21T01:43:14.313 回答
1
 if teststring.split():
      print "not only whitespace!" 
 else:
     print ":("
于 2012-06-21T01:43:10.620 回答