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

if myString == string.empty:

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


当前回答

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

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

其他回答

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

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

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

因此,您应该使用:

if not some_string:

or:

if some_string:

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

如果您不完全确定您的输入是否真的是字符串,我建议您另外使用isinstance(object,classinfo)链接,如示例所示。

如果不是,列表或True布尔值也可以计算为True。

<script type=“text/javascript”src=“//cdn.datacamp.com/dcl react.js.gz”></script><div data datacamp练习数据lang=“python”><code data type=“样本代码”>定义测试字符串(my_string):如果isinstance(my_string,str)和my_string:print(“这是我,字符串!->”+my_String)其他:print(“不,不,字符串”)def not_fully_test_string(my_string):如果my_string:print(“这是我,String???->”+str(my_String))其他:print(“不,不,字符串”)print(“测试字符串:”)test_string(“”)test_string(真)测试字符串([“string1”,“string2”])test_string(“我的字符串”)test_string(“”)print(“\n是否测试字符串?”)not_fully_test_string(“”)not_fully_test_string(真)not_fully_test_string([“string1”,“string2”])not_fully_test_string(“我的字符串”)not_fully_test_string(“”)</code></div>

not str(myString)

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

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