Python是否有类似空字符串变量的功能,您可以在其中执行以下操作:
if myString == string.empty:
无论如何,检查空字符串值最优雅的方法是什么?我发现每次检查空字符串的硬编码“”都不太好。
Python是否有类似空字符串变量的功能,您可以在其中执行以下操作:
if myString == string.empty:
无论如何,检查空字符串值最优雅的方法是什么?我发现每次检查空字符串的硬编码“”都不太好。
当前回答
当您逐行读取文件并想确定哪一行是空的时,请确保使用.strip(),因为“空”行中有换行符:
lines = open("my_file.log", "r").readlines()
for line in lines:
if not line.strip():
continue
# your code for non-empty lines
其他回答
我对“”、“”和“\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()
如果需要,将其包装在方法定义中。
PEP 8中“编程建议”部分:
对于序列(字符串、列表、元组),请使用空序列为false的事实。
因此,您应该使用:
if not some_string:
or:
if some_string:
为了澄清,如果序列为空或不为空,则在布尔上下文中将其求值为False或True。它们不等于False或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的字段。在我的例子中,这是由于一个复合主键)。
正如prmatta在上面发布的,但有错误。
def isNoneOrEmptyOrBlankString (myString):
if myString:
if not myString.strip():
return True
else:
return False
return False
我会在剥离之前测试无。此外,我将使用空字符串为False(或Falsy)的事实。这种方法类似于Apache的StringUtils.isBlank或Guava的Strings.isNullOrEmpty
这是我用来测试字符串是否为None或Empty或Blank的方法:
def isBlank (myString):
return not (myString and myString.strip())
如果字符串不是None NOR Empty NOR Blank,则与测试正好相反:
def isNotBlank (myString):
return bool(myString and myString.strip())