在Python中从字符串转换为布尔值? [英] Converting from a string to boolean in 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中从字符串转换为布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!