如何检查一个str(变量)是否为空? [英] How to check whether a str(variable) is empty or not?
问题描述
我如何制作:
if str(variable) == [contains text]:
条件?
(或某些原因,因为我敢肯定我刚才写的东西是完全错误的)
(or something, because I am pretty sure that what I just wrote is completely wrong)
我是尝试检查列表中的 random.choice
是否为 [,]
(空白)或包含 [ text,]
。
I am sort of trying to check if a random.choice
from my list is ["",]
(blank) or contains ["text",]
.
推荐答案
您可以比较一下字符串转换为空字符串:
You could just compare your string to the empty string:
if variable != "":
etc.
但是您可以将其缩写为:
But you can abbreviate that as follows:
if variable:
etc.
说明:An 如果
实际上是通过为您提供的逻辑表达式计算值来工作的: True
或 False
。如果仅使用变量名(或诸如 hello之类的文字字符串)代替逻辑测试,则规则是:空字符串计为False,所有其他字符串计为True。空列表和数字零也算作假,其他大多数情况也算作真。
Explanation: An if
actually works by computing a value for the logical expression you give it: True
or False
. If you simply use a variable name (or a literal string like "hello") instead of a logical test, the rule is: An empty string counts as False, all other strings count as True. Empty lists and the number zero also count as false, and most other things count as true.
这篇关于如何检查一个str(变量)是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!