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

字符串的例子:

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


当前回答

我使用以下方法:

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

其他回答

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

使用下面的简单代码

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

与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

检查split()方法给出的列表的长度。

if len(your_string.split()==0:
     print("yes")

或 比较strip()方法的输出与null。

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

我使用以下方法:

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