Python是否有类似空字符串变量的功能,您可以在其中执行以下操作:

if myString == string.empty:

无论如何,检查空字符串值最优雅的方法是什么?我发现每次检查空字符串的硬编码“”都不太好。


当前回答

not str(myString)

对于空字符串,此表达式为True。非空字符串、None和非字符串对象都将产生False,但需要注意的是,对象可能会重写__str__,通过返回一个falsy值来阻止此逻辑。

其他回答

if-stringname:当字符串为空时,返回false。我想再简单不过了。

回复@1290。抱歉,无法格式化注释中的块。None值在Python中不是空字符串,也不是(空格)。安德鲁·克拉克的答案是正确的:如果不是myString。@rouble的答案是特定于应用程序的,不会回答OP的问题。如果你对什么是“空白”字符串采用一个特殊的定义,你会遇到麻烦。特别是,标准行为是str(None)生成“None”,一个非空字符串。

但是,如果您必须将None和(空格)视为“空白”字符串,这里有一个更好的方法:

class weirdstr(str):
    def __new__(cls, content):
        return str.__new__(cls, content if content is not None else '')
    def __nonzero__(self):
        return bool(self.strip())

示例:

>>> normal = weirdstr('word')
>>> print normal, bool(normal)
word True

>>> spaces = weirdstr('   ')
>>> print spaces, bool(spaces)
    False

>>> blank = weirdstr('')
>>> print blank, bool(blank)
 False

>>> none = weirdstr(None)
>>> print none, bool(none)
 False

>>> if not spaces:
...     print 'This is a so-called blank string'
... 
This is a so-called blank string

满足@rouble要求,同时不破坏字符串的预期布尔行为。

以下是适用于任意数量空间的优雅解决方案。

def str_empty(s: str) -> bool:
    """Strip white space and count remaining characters."""
    return len(s.strip()) < 1


>>> str_empty(' ')
True

对于那些期望类似apacheStringUtils.isBlank或Guava Strings.isNullOrEmpty的行为的人:

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

最清晰的方法是:

if s == "":

优点:

向编程器提供应为什么类型的附加指示。“”不是“硬编码”,它是一个神奇的值,比x==0更大。有些值是基本的,不需要命名常量;例如,x%2以检查偶数。不能错误地指示任何错误值(例如[])为空字符串。


考虑如何检查整数是否为0:

if x == 0:

人们当然不应该这样做:

if not x:

整数和字符串都是基元值类型。为什么要区别对待他们?