Converting from a string to boolean in Python?(在 Python 中从字符串转换为布尔值?)
问题描述
有谁知道如何在 Python 中将字符串转换为布尔值?我发现 这个链接.但这看起来不是正确的方法.IE.使用内置功能等.
Does anyone know how to do convert from a string to a boolean in Python? I found this link. But it doesn't look like a proper way to do it. I.e. using built-in functionality, etc.
我之所以问这个是因为我从这里了解了 int("string")
.但是当尝试 bool("string")
它总是返回 True
:
The reason I'm asking this is because I learned about int("string")
from here. But when trying bool("string")
it always returns True
:
>>> bool("False")
True
推荐答案
真的,您只需将字符串与您期望接受的表示 true 的字符串进行比较,因此您可以这样做:
Really, you just compare the string to whatever you expect to accept as representing true, so you can do this:
s == 'True'
或检查一大堆值:
s.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
使用以下内容时要小心:
Be cautious when using the following:
>>> bool("foo")
True
>>> bool("")
False
空字符串评估为 False
,但其他所有字符串评估为 True
.所以这不应该用于任何类型的解析目的.
Empty strings evaluate to False
, but everything else evaluates to True
. So this should not be used for any kind of parsing purposes.
这篇关于在 Python 中从字符串转换为布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中从字符串转换为布尔值?


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01