检查字符串是否仅包含空白字符

300

如何判断一个字符串是否只包含空格?

示例字符串:

  • " " (空格,空格,空格)

  • " \t \n " (空格,制表符,换行符,空格)

  • "\n\n\n\t\n" (换行符,换行符,换行符,制表符,换行符)


换行符是否算作空格?制表符应该是一个或多个空格。 - Timo
11个回答

419

使用str.isspace()方法:

如果字符串中只有空格字符且至少有一个字符,则返回True,否则返回False

如果字符在Unicode字符数据库(见unicodedata)中的一般类别为Zs(“分隔符,空格”),或其双向类别为WS、B或S之一,则该字符为空格。

将其与处理空字符串的特殊情况相结合。

或者,您可以使用str.strip()并检查结果是否为空。


如果字符串包含不间断空格字符U+00A0或者ALT+160,这段代码在Python 2.4上会失败。但是在Python 2.7中已经修复了这个问题。 - Kumba
43
请记住,这不会检查None'' - Parth Mehrotra
1
在Python 2.7.13中,isspace()将把非断行空格视为空格。不错! - Iching Chang
2
你也可能想要排除空字符串,那么你可以这样做:if len(str) == 0 or str.isspace(): - Joe
"".isspace() 返回 False 真的是一个非常大的 WTF。 - Timmmm
显示剩余2条评论

77

str.isspace() 对于一个有效且为空的字符串返回 False

>>> tests = ['foo', ' ', '\r\n\t', '']
>>> print([s.isspace() for s in tests])
[False, True, True, False]

因此,使用not进行检查也将评估None类型和''""(空字符串)。
>>> tests = ['foo', ' ', '\r\n\t', '', None, ""]
>>> print ([not s or s.isspace() for s in tests])
[False, True, True, True, True, True]

1
为什么选择让它在输入None时返回True - AMC

38

你想使用isspace()方法。

str.isspace()

如果字符串中只包含空格字符且至少有一个字符,则返回true,否则返回false。

这个方法适用于所有字符串对象。以下是针对您特定用例的使用示例:

if aStr and (not aStr.isspace()):
    print aStr

2
这不是与当前的顶部和被接受的答案相同的解决方案吗? - AMC

26

14

6
检查由split()方法给出的列表的长度。
if len(your_string.split()==0:
     print("yes")

或者将strip()方法的输出与null进行比较。

if your_string.strip() == '':
     print("yes")

1
没有理由拆分字符串,len() 适用于字符串。此外,OP 并不是在询问如何测试空字符串,而是要测试一个全为空格的字符串。你的第二种方法也不错。此外,在 Python 中,条件语句周围的括号是不必要的。 - NeilK
1
奇怪的是,第一种方法实际上是检查没有空格字符的好方法,如果你将==0替换为==1 - Mad Physicist
if len(your_string.split())==0: --> if not your_string.split():, if your_string.strip() == '': --> if not your_string.strip():。无论哪种情况,第一种方法都不如现有的解决方案好,而第二种方法已经在其他答案中提到过了。 - AMC

3

类似于C#字符串静态方法isNullOrWhiteSpace。

def isNullOrWhiteSpace(str):
  """Indicates whether the specified string is null or empty string.
     Returns: True if the str parameter is null, an empty string ("") or contains 
     whitespace. Returns false otherwise."""
  if (str is None) or (str == "") or (str.isspace()):
    return True
  return False

isNullOrWhiteSpace(None) -> True // None equals null in c#, java, php
isNullOrWhiteSpace("")   -> True
isNullOrWhiteSpace(" ")  -> True

你可以直接写成 return (str is None) or (str == "") or (str.isspace()) - Alexander
哦,还有None""都是假的,所以你可以这样写:return not str or str.isspace() - Alexander
@AMC,您能详细说明一下吗?我不明白您想表达什么。 - broadband

3

这里是一个适用于所有情况的解决方案:

def is_empty(s):
    "Check whether a string is empty"
    return not s or not s.strip()

如果变量为None,则会在not s处停止并且不再进一步进行评估(因为not None == True)。显然,strip()方法处理了制表符、换行符等常见情况。

由于 not None == True 会产生歧义,最好直接说 None is False。此外,这种比较不应使用 == - AMC

2
我使用了以下内容:

我使用了以下内容:

if str and not str.isspace():
  print('not null and not empty nor whitespace')
else:
  print('null or empty or whitespace')

你是指 None 吗? - AMC

2

我假设在您的情况下,空字符串是一个真正为空或只包含所有空格的字符串。

if(str.strip()):
    print("string is not empty")
else:
    print("string is empty")

请注意,这不会检查None

这个问题不是已经被现有的答案所覆盖了吗? - AMC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接