python 中的 string.IsNullOrWhiteSpace 等效项

use*_*007 2 python

我是 python 新手,想在 python 中找到C# string.IsNullOrWhiteSpace的等效项。通过有限的网络搜索,我创建了以下函数

def isNullOrWhiteSpace(str):
  return not str or not str.strip()  

print "Result: " + isNullOrWhiteSpace("Test")
print "Result: " + isNullOrWhiteSpace(" ")
#print "Result: " + isNullOrWhiteSpace() #getting TypeError: Cannot read property 'mp$length' of undefined
Run Code Online (Sandbox Code Playgroud)

但这是打印

Result: undefined
Result: undefined
Run Code Online (Sandbox Code Playgroud)

我想尝试一下如果没有传递任何值它会如何表现。不幸的是,我正在获取TypeError: Cannot read property 'mp$length' of undefined注释行。有人可以帮助我处理这些情况吗?

Dav*_*d S 5

您可以使用以下命令执行以下操作isspace

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

str.isspace()

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

空函数调用与传递给它不同None,因此您可以为此特定情况设置默认值。

在你的情况下类似:

def isNullOrWhiteSpace(str=None):
  return not str or str.isspace()

print("Result: ", isNullOrWhiteSpace("Test"))  #False
print("Result: ", isNullOrWhiteSpace(" "))  #True 
print("Result: ", isNullOrWhiteSpace())  #True
Run Code Online (Sandbox Code Playgroud)