检查字符串是否仅包含空白字符
我该如何测试一个字符串是否只包含空白字符呢?
下面是一些示例字符串:
" "
(空格,空格,空格)" \t \n "
(空格,制表符,空格,换行,空格)"\n\n\n\t\n"
(换行,换行,换行,制表符,换行)
11 个回答
39
你想使用 isspace()
这个方法。
str.isspace()
如果字符串中只有空白字符,并且至少有一个字符,就返回真;否则返回假。
这个方法适用于每个字符串对象。下面是一个针对你具体情况的使用示例:
if aStr and (not aStr.isspace()):
print aStr
78
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]
421
使用 str.isspace()
方法:
如果字符串里只有空白字符,并且至少有一个字符,就返回
True
;否则返回False
。空白字符是指在Unicode字符数据库中(可以查看 unicodedata),它的类别是 Zs(“分隔符,空格”),或者它的双向类别是 WS、B 或 S 之一。
可以结合这个方法来处理空字符串的特殊情况。
另外,你也可以使用 str.strip()
方法,然后检查结果是否为空。