如何在Python中测试字符串是否为空?

例如,

"<space><space><space>" 是空的,也是

"<space><tab><space><newline><space>", ,也是如此

"<newline><newline><newline><tab><newline>", , ETC。

有帮助吗?

解决方案

yourString.isspace()

“是否有字符串中只有空白字符和有至少一个字符,否则返回假,则返回真。”

联合,与用于处理空字符串的一个特例。

可替换地,可以使用

strippedString = yourString.strip()

和然后检查是否strippedString是空的。

其他提示

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

您想使用 isspace() 方法

  

海峡的 isspace为()

     

如果有字符串中只有空白字符,则返回true和   有至少一个字符,否则返回假。

这是每个字符串对象中定义。在这里它是为特定使用情况下的使用例:

if aStr and (not aStr.isspace()):
    print aStr

对于那些期望像 apache 那样的行为的人 StringUtils.isBlank 或番石榴 Strings.isNullOrEmpty :

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

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

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

或者 比较条()方法的输出与空。

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

下面是一个答案应该适用于所有情况:

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

如果该变量是None,它将停止在not sand不进一步评估(自not None == True)。显然,需要strip()method的制表符,换行符等的通常情况下,护理

我假设在你的情况下,空字符串是包含所有空格的字符串,是真正为空或1。

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

请注意这不检查None

我使用以下内容:

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)

相似性用C#字符串静态方法isNullOrWhiteSpace。

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top