gpt4 book ai didi

python - python 中的 string.IsNullOrWhiteSpace 等效项

转载 作者:行者123 更新时间:2023-12-02 19:16:25 25 4
gpt4 key购买 nike

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

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

但是这是打印

Result: undefined
Result: undefined

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

最佳答案

您可以使用isspace执行以下操作:

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

str.isspace()

Return true if there are only whitespace characters in the string andthere is at least one character, false otherwise.

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

在你的情况下,类似:

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

print("Result: ", isNullOrWhiteSpace("Test")) #False
print("Result: ", isNullOrWhiteSpace(" ")) #True
print("Result: ", isNullOrWhiteSpace()) #True

关于python - python 中的 string.IsNullOrWhiteSpace 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63654215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com