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

if myString == string.empty:

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


当前回答

您可能会看到Python中的“分配空值或字符串”

这是关于比较空字符串的。因此,你可以测试你的字符串是否等于空字符串,而不是用not测试空字符串。。。

其他回答

测试空字符串或空白字符串(更短的方式):

if myString.strip():
    print("it's not an empty or blank string")
else:
    print("it's an empty or blank string")

最优雅的方法可能是简单地检查它是真是假,例如:

if not my_string:

但是,您可能需要删除空白,因为:

 >>> bool("")
 False
 >>> bool("   ")
 True
 >>> bool("   ".strip())
 False

但是,您可能应该对此更加明确一点,除非您确定该字符串已通过某种验证,并且是可以通过这种方式测试的字符串。

我曾经写过类似于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 var1 

无法将布尔值为False的变量与空字符串“”进行区分:

var1 = ''
not var1
> True

var1 = False
not var1
> True

但是,如果向脚本中添加一个简单的条件,则会产生差异:

var1  = False
not var1 and var1 != ''
> True

var1 = ''
not var1 and var1 != ''
> 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要求,同时不破坏字符串的预期布尔行为。