如何测试字符串是否只包含空格?
字符串的例子:
" "(空格,空格,空格) " \t \n "(空格,制表符,空格,换行符,空格) "\n\n\ t\n"(换行符,换行符,制表符,换行符)
如何测试字符串是否只包含空格?
字符串的例子:
" "(空格,空格,空格) " \t \n "(空格,制表符,空格,换行符,空格) "\n\n\ t\n"(换行符,换行符,制表符,换行符)
当前回答
与c#字符串静态方法类似的是nullorwhitespace。
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
其他回答
您需要使用isspace()方法
str.isspace () 如果字符串中只有空白字符,则返回true 至少有一个字符,否则为假。
在每个字符串对象上都有定义。下面是一个特定用例的使用示例:
if aStr and (not aStr.isspace()):
print aStr
您可以使用str.isspace()方法。
与c#字符串静态方法类似的是nullorwhitespace。
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
检查字符串是否是空格或换行符
使用下面的简单代码
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.strip()):
print("string is not empty")
else:
print("string is empty")
注意,这不会检查None