Python是否有类似空字符串变量的功能,您可以在其中执行以下操作:
if myString == string.empty:
无论如何,检查空字符串值最优雅的方法是什么?我发现每次检查空字符串的硬编码“”都不太好。
Python是否有类似空字符串变量的功能,您可以在其中执行以下操作:
if myString == string.empty:
无论如何,检查空字符串值最优雅的方法是什么?我发现每次检查空字符串的硬编码“”都不太好。
当前回答
如果要检查字符串是否完全为空
if not mystring
因为空字符串为false但如果字符串仅为空白,则为真,因此您可能希望
if not mystring.strip()
其他回答
如果要检查字符串是否完全为空
if not mystring
因为空字符串为false但如果字符串仅为空白,则为真,因此您可能希望
if not mystring.strip()
空字符串是“falsy”(python 2或python 3引用),这意味着它们在布尔上下文中被视为false,因此您可以这样做:
if not myString:
如果知道变量是字符串,这是首选方法。如果变量也可以是其他类型,则应使用:
if myString == "":
有关布尔上下文中为假的其他值,请参阅真值测试文档。
如果这对某人有用,这里有一个我构建的快速函数,用于将列表列表中的空白字符串替换为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的字段。在我的例子中,这是由于一个复合主键)。
最优雅的方法可能是简单地检查它是真是假,例如:
if not my_string:
但是,您可能需要删除空白,因为:
>>> bool("")
False
>>> bool(" ")
True
>>> bool(" ".strip())
False
但是,您可能应该对此更加明确一点,除非您确定该字符串已通过某种验证,并且是可以通过这种方式测试的字符串。
对于那些期望类似apacheStringUtils.isBlank或Guava Strings.isNullOrEmpty的行为的人:
if mystring and mystring.strip():
print "not blank string"
else:
print "blank string"