You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将字符串型'True'/'False'转换为布尔值?

将字符串列表中的'True'/'False'转换为布尔值列表

要把包含字符串形式'True'/'False'的列表转换成布尔值列表,不能直接用bool()函数(因为任何非空字符串都会被转为True,包括'False'),推荐以下几种可靠的方法:

方法1:列表推导式(最直观)

直接判断每个字符串元素是否等于'True',生成布尔值列表:

tf = ['True', 'False', 'False']
bool_list = [x == 'True' for x in tf]

# 验证结果
print(bool_list)          # 输出: [True, False, False]
print(type(bool_list[0])) # 输出: <class 'bool'>

方法2:使用map+lambda

通过map函数批量处理每个元素,再转为列表:

tf = ['True', 'False', 'False']
bool_list = list(map(lambda x: x == 'True', tf))

方法3:兼容大小写的转换

如果列表中存在大小写不统一的情况(比如'true'、'TRUE'),可以先转小写再判断:

tf = ['True', 'false', 'FALSE']
bool_list = [x.lower() == 'true' for x in tf]
# 输出: [True, False, False]

内容的提问来源于stack exchange,提问作者Cason Mercadejas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:55:18