Python是否有类似空字符串变量的功能,您可以在其中执行以下操作:
if myString == string.empty:
无论如何,检查空字符串值最优雅的方法是什么?我发现每次检查空字符串的硬编码“”都不太好。
Python是否有类似空字符串变量的功能,您可以在其中执行以下操作:
if myString == string.empty:
无论如何,检查空字符串值最优雅的方法是什么?我发现每次检查空字符串的硬编码“”都不太好。
当前回答
我曾经写过类似于Bartek的答案和javascript的灵感:
def is_not_blank(s):
return bool(s and not s.isspace())
测试:
print is_not_blank("") # False
print is_not_blank(" ") # False
print is_not_blank("ok") # True
print is_not_blank(None) # False
其他回答
我对“”、“”和“\n”等字符串进行了一些实验。当且仅当变量foo是至少包含一个非空白字符的字符串时,我希望isNotWhitespace为True。我使用的是Python 3.6。以下是我的结论:
isWhitespace = str is type(foo) and not foo.strip()
isNotWhitespace = str is type(foo) and not not foo.strip()
如果需要,将其包装在方法定义中。
您可能会看到Python中的“分配空值或字符串”
这是关于比较空字符串的。因此,你可以测试你的字符串是否等于空字符串,而不是用not测试空字符串。。。
以下是适用于任意数量空间的优雅解决方案。
def str_empty(s: str) -> bool:
"""Strip white space and count remaining characters."""
return len(s.strip()) < 1
>>> str_empty(' ')
True
我曾经写过类似于Bartek的答案和javascript的灵感:
def is_not_blank(s):
return bool(s and not s.isspace())
测试:
print is_not_blank("") # False
print is_not_blank(" ") # False
print is_not_blank("ok") # True
print is_not_blank(None) # False
not str(myString)
对于空字符串,此表达式为True。非空字符串、None和非字符串对象都将产生False,但需要注意的是,对象可能会重写__str__,通过返回一个falsy值来阻止此逻辑。