如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
当前回答
实际上,你只是将字符串与你期望接受的表示true的字符串进行比较,所以你可以这样做:
s == 'True'
或者检查一大堆值:
s.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
使用以下物品时请谨慎:
>>> bool("foo")
True
>>> bool("")
False
空字符串的值是False,但其他的值都是True。所以这个不应该用于任何解析目的。
其他回答
使用这个解决方案:
def to_bool(value) -> bool:
if value == 'true':
return True
elif value == 'True':
return True
elif value == 'false':
return False
elif value == 'False':
return False
elif value == 0:
return False
elif value == 1:
return True
else:
raise ValueError("Value was not recognized as a valid Boolean.")
下面是我用来评估字符串真实性的东西:
def as_bool(val):
if val:
try:
if not int(val): val=False
except: pass
try:
if val.lower()=="false": val=False
except: pass
return bool(val)
与使用eval的结果大致相同,但更安全。
一个很酷,简单的技巧(基于@Alan Marchiori的帖子),但使用yaml:
import yaml
parsed = yaml.load("true")
print bool(parsed)
如果这个范围太广,可以通过测试类型结果进行细化。如果yaml返回的类型是str,那么它就不能转换为任何其他类型(我能想到的类型),所以可以单独处理它,或者让它为真。
我不会对速度做任何猜测,但因为我在Qt gui下使用yaml数据,这有一个很好的对称性。
在有限的情况或情况下,您可以对正在处理的数据做出强有力的假设。然而,由于自定义对象可以覆盖Python中的__eq__相等性检查,因此存在一个重要的陷阱。看看下面这个刻意简化的玩具例子:
In [1]: class MyString:
...: def __init__(self, value):
...: self.value = value
...: def __eq__ (self, obj):
...: if hasattr(obj, 'value'):
...: return obj.value == self.value
...: return False
...:
In [2]: v = MyString("True")
In [3]: v == "True"
Out[3]: False
如果你想象有人继承了MyString的字符串类型,或者实现了各种原生字符串方法,repr等,这样MyString实例的行为就和字符串完全一样,但是在相等性检查中有特殊的额外值步骤,那么简单地使用== 'True'将会失败,而且从用户的角度来看,这很可能是一个无声的失败。
这就是为什么将type强制转换为您想要执行的相等性检查的确切性质,将其封装到一个helper函数中,并对依赖这种“已注册”的方式进行验证是一种很好的实践。例如,在MyString中,你可以这样写,
def validate(s):
if isinstance(s, str):
return s == 'True'
elif isinstance(s, MyString):
return s.value == 'True' # <-- business logic
...
raise ValueError(f"Type {type(s)} not supported for validation.")
或者另一种常用的模式是反向透视图,其中您只为验证定义了一种行为,但是您有一个helper函数,它将强制转换为适合于该单一验证行为的类型,例如
def to_str(s):
if isinstance(s, str):
return s
elif isinstance(s, MyString):
return s.value
...
raise ValueError(f"Unsupported type {type(s)}")
def validate(s):
return to_str(s) == 'True'
It might look like we're adding a lot of boilerplate and verbosity. We could glibly express critique by saying, "why write all that if you can just write s == 'True'?" - But it misses the point that when you are validating something, you need to make sure all of your preconditions hold for the validation logic to be applied. If you can assume some data is a plain str type and you don't need to do any of that precondition (such as type) checking, great - but that's a very rare situation and it can be misleading to characterize the general situation for this question as being amenable to one super short and concise equality check.
如果你可以控制返回true/false的实体,一种选择是让它返回1/0而不是true/false,那么:
boolean = bool(int(response))
额外的转换为int处理来自网络的响应,这些响应总是字符串。
2021年更新:“which are always string”——这是一个幼稚的观察。它取决于库使用的序列化协议。高级库(大多数web开发人员使用的库)的默认序列化通常是在序列化为字节之前转换为字符串。然后在另一边,它从字节反序列化为字符串,所以你丢失了任何类型信息。