在非空白页上测试字符串内容

2024-03-29 10:31:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 内容onlylenifspace字符elsesomething
1条回答
网友
1楼 · 发布于 2024-03-29 10:31:20

字符串有一个名为^{}的方法,根据文档:

Return[s] true if there are only whitespace characters in the string and there is at least one character, false otherwise.

所以,这意味着:

if teststring.isspace():
    # contains only whitespace

会做你想做的。

网友
2楼 · 发布于 2024-03-29 10:31:20

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

  if teststring.strip():
      # non blank line
  else:
      # blank line
网友
3楼 · 发布于 2024-03-29 10:31:20

你可以使用.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.

相关问题 更多 >