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

字符串的例子:

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


当前回答

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

使用下面的简单代码

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)

其他回答

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]

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

使用下面的简单代码

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)

这里有一个在所有情况下都适用的答案:

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

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

我假设在您的场景中,空字符串是真正为空的字符串或包含所有空白的字符串。

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

注意,这不会检查None

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