How to check whether a str(variable) is empty or not?(如何检查 str(variable) 是否为空?)
问题描述
如何制作:
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.
但你可以缩写如下:
if variable:
etc.
说明:if 实际上是通过计算您给它的逻辑表达式的值来工作的:True 或 False.如果您只是使用变量名(或hello"之类的文字字符串)而不是逻辑测试,则规则是:空字符串计为 False,所有其他字符串计为 True.空列表和数字 0 也算作假,而其他大多数情况都算作真.
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(variable) 是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查 str(variable) 是否为空?
基础教程推荐
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
