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

use*_*670 63 python string conditional-statements

我如何制作:

if str(variable) == [contains text]:
Run Code Online (Sandbox Code Playgroud)

条件?

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

我有点试图检查random.choice我的列表中是否["",](空白)或包含["text",].

ale*_*xis 121

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

if variable != "":
    etc.
Run Code Online (Sandbox Code Playgroud)

但您可以将其缩写如下:

if variable:
    etc.
Run Code Online (Sandbox Code Playgroud)

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


Dan*_*rov 17

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

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


bri*_*ice 13

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

>>> if not "":
...     print("empty")
...
empty
Run Code Online (Sandbox Code Playgroud)


sen*_*rle 9

只是说if sif not s.如在

s = ''
if not s:
    print 'not', s
Run Code Online (Sandbox Code Playgroud)

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

>>> 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
Run Code Online (Sandbox Code Playgroud)


kam*_*sar 7

有时我们在引号之间有更多空格,然后使用这种方法

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

if not a.strip():
    print("String is empty")
else:
    print("String is not empty")
Run Code Online (Sandbox Code Playgroud)


Tha*_*ran 6

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

>>> bool(None)
False
>>> bool("")
False
>>> bool("a")
True
>>> bool("ab")
True
>>> bool("9")
True
Run Code Online (Sandbox Code Playgroud)