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

if myString == string.empty:

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


当前回答

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

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

其他回答

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

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

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

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

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


>>> str_empty(' ')
True

如果这对某人有用,这里有一个我构建的快速函数,用于将列表列表中的空白字符串替换为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的字段。在我的例子中,这是由于一个复合主键)。

当您逐行读取文件并想确定哪一行是空的时,请确保使用.strip(),因为“空”行中有换行符:

lines = open("my_file.log", "r").readlines()

for line in lines:
    if not line.strip():
        continue

    # your code for non-empty lines