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

if myString == string.empty:

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


当前回答

空字符串是“falsy”(python 2或python 3引用),这意味着它们在布尔上下文中被视为false,因此您可以这样做:

if not myString:

如果知道变量是字符串,这是首选方法。如果变量也可以是其他类型,则应使用:

if myString == "":

有关布尔上下文中为假的其他值,请参阅真值测试文档。

其他回答

我对“”、“”和“\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()

如果需要,将其包装在方法定义中。

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

PEP 8中“编程建议”部分:

对于序列(字符串、列表、元组),请使用空序列为false的事实。

因此,您应该使用:

if not some_string:

or:

if some_string:

为了澄清,如果序列为空或不为空,则在布尔上下文中将其求值为False或True。它们不等于False或True。

回复@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要求,同时不破坏字符串的预期布尔行为。

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

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