如何检查一个str(variable)是否为空?

110

我如何制作:

if str(variable) == [contains text]:

判断条件?

(或其他什么,因为我很确定我刚写的完全是错的)

我有一个列表,想要检查从列表中 random.choice 是否是["",](空白)或包含["text",]


你的意思是 if str(variable) == "my text": 吗? - Simon Bergot
你似乎有点困惑,我建议你阅读一下Python教程 - Rik Poggi
3
可能是Python中检查字符串是否为空的最优雅方法?的重复问题。 - Ronak Shah
14个回答

2
{
test_str1 = "" 
test_str2 = "  "
  
# checking if string is empty 
print ("The zero length string without spaces is empty ? : ", end = "") 
if(len(test_str1) == 0): 
    print ("Yes") 
else : 
    print ("No") 
  
# prints No  
print ("The zero length string with just spaces is empty ? : ", end = "") 
if(len(test_str2) == 0): 
    print ("Yes") 
else : 
    print ("No") 
}

2

在if-else语句中使用"not"

x = input()

if not x:
   print("Value is not entered")
else:
   print("Value is entered")

1
Python字符串是不可变的,因此在讨论其操作时需要更复杂的处理。请注意,带有空格的字符串实际上是一个空字符串,但具有非零大小。 让我们看看两种不同的检查字符串是否为空的方法: 方法#1:使用Len() 使用Len()是检查零长度字符串的最常用方法。即使它忽略了仅包含空格的字符串实际上也应该被视为一个空字符串,即使它是非零的。 方法#2:使用not Not运算符也可以执行类似于Len()的任务,并检查0长度字符串,但与上述相同,它认为仅包含空格的字符串也是非空的,这在实践中不应该是真的。 祝你好运!

0
#empty variable
myvar = ""

#check if variable is empty
if not myvar:
    print("variable is empty") # variable is empty

1
这已经在这里建议过了(https://dev59.com/Zmkw5IYBdhLWcg3wZJp9#9926470)。 - rachwa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接