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

if myString == string.empty:

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


当前回答

如果您想区分空字符串和空字符串,我建议使用If-len(string),否则,我建议像其他人所说的那样简单地使用If-string。但是,关于充满空格的字符串的警告仍然适用,所以不要忘记剥离。

其他回答

如果您想区分空字符串和空字符串,我建议使用If-len(string),否则,我建议像其他人所说的那样简单地使用If-string。但是,关于充满空格的字符串的警告仍然适用,所以不要忘记剥离。

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

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

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

如果这对某人有用,这里有一个我构建的快速函数,用于将列表列表中的空白字符串替换为N/a(python 2)。

y = [["1","2",""],["1","4",""]]

def replace_blank_strings_in_lists_of_lists(list_of_lists):
    new_list = []
    for one_list in list_of_lists:
        new_one_list = []
        for element in one_list:
            if element:
                new_one_list.append(element)
            else:
                new_one_list.append("N/A")
        new_list.append(new_one_list)
    return new_list


x= replace_blank_strings_in_lists_of_lists(y)
print x

这对于将列表列表发布到mysql数据库非常有用,该数据库不接受某些字段的空格(在模式中标记为NN的字段。在我的例子中,这是由于一个复合主键)。

如果你只是使用

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