如何测试字符串是否只包含空格?

字符串的例子:

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


当前回答

使用str.isspace()方法:

如果字符串中只有空格字符且至少有一个字符,则返回True,否则返回False。 如果一个字符在Unicode字符数据库(参见unicodedata)中,它的一般类别是Zs(“分隔符,空格”),或者它的双向类是WS、B或S之一,那么它就是空白字符。

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

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

其他回答

对于那些期望类似apache StringUtils的行为的人。是空白或番石榴弦。isNullOrEmpty:

if mystring and mystring.strip():
    print "not blank string"
else:
    print "blank string"

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

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

因此,使用not检查也会计算None Type和" or ""(空字符串)

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

您可以使用str.isspace()方法。

检查字符串是否是空格或换行符

使用下面的简单代码

mystr = "      \n  \r  \t   "
if not mystr.strip(): # The String Is Only Spaces!
    print("\n[!] Invalid String !!!")
    exit(1)
mystr = mystr.strip()
print("\n[*] Your String Is: "+mystr)

我使用以下方法:

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