如何检查str(变量)是否为空?

时间:2012-03-29 13:34:23

标签: python string conditional-statements

我如何制作:

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

条件?

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

我正在尝试检查列表中的random.choice["",](空白)还是包含["text",]

13 个答案:

答案 0 :(得分:108)

您可以将字符串与空字符串进行比较:

if variable != "":
    etc.

但您可以将其缩写如下:

if variable:
    etc.

说明:if实际上是通过计算您为其提供的逻辑表达式的值来实现的:TrueFalse。如果您只是使用变量名称(或像“hello”这样的文字字符串)而不是逻辑测试,则规则为:空字符串计为False,所有其他字符串计为True。空列表和数字零也算作假,大多数其他事情都算为真。

答案 1 :(得分:13)

检查字符串是否为空的“Pythonic”方法是:

import random
variable = random.choice(l)
if variable:
    # got a non-empty string
else:
    # got an empty string

答案 2 :(得分:10)

默认情况下,空字符串为False:

>>> if not "":
...     print("empty")
...
empty

答案 3 :(得分:7)

只需说出if sif not s即可。如在

s = ''
if not s:
    print 'not', s

所以在你的具体例子中,如果我理解正确的话......

>>> import random
>>> l = ['', 'foo', '', 'bar']
>>> def default_str(l):
...     s = random.choice(l)
...     if not s:
...         print 'default'
...     else:
...         print s
... 
>>> default_str(l)
default
>>> default_str(l)
default
>>> default_str(l)
bar
>>> default_str(l)
default

答案 4 :(得分:4)

element = random.choice(myList)
if element:
    # element contains text
else:
    # element is empty ''

答案 5 :(得分:3)

对于python 3,您可以使用bool()

>>> bool(None)
False
>>> bool("")
False
>>> bool("a")
True
>>> bool("ab")
True
>>> bool("9")
True

答案 6 :(得分:2)

  

如何制作:if str(variable) == [contains text]:条件?

也许最直接的方式是:

if str(variable) != '':
  # ...

请注意,if not ...解决方案会测试相反的条件。

答案 7 :(得分: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") 
}

答案 8 :(得分:1)

有时候引号之间会有更多空格,然后使用这种方法

a = "   "
>>> bool(a)
True
>>> bool(a.strip())
False

if not a.strip():
    print("String is empty")
else:
    print("String is not empty")

答案 9 :(得分:1)

在if-else中使用“

x = input()

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

答案 10 :(得分:1)

Python 字符串是不可变的,因此在讨论其操作时有更复杂的处理。请注意,带空格的字符串实际上是一个空字符串,但大小不为零。 让我们看看检查字符串是否为空的两种不同方法: 方法#1:使用Len() 使用 Len() 是检查零长度字符串的最通用方法。即使它忽略了这样一个事实,即只有空格的字符串实际上也应该被视为空字符串,即使它的非零也是如此。

方法#2:不使用

Not 运算符也可以执行类似于 Len() 的任务,并检查长度为 0 的字符串,但与上面相同,它认为只有空格的字符串也是非空的,这实际上不应该是真的。

祝你好运!

答案 11 :(得分:0)

如果变量包含文本,则:

len(variable) != 0

它没有

len(variable) == 0

答案 12 :(得分:0)

string = "TEST"
try:
  if str(string):
     print "good string"
except NameError:
     print "bad string"