如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
当前回答
我不同意任何解决办法,因为他们太宽容了。在解析字符串时,这通常不是您想要的结果。
这里是我使用的解决方案:
def to_bool(bool_str):
"""Parse the string and return the boolean value encoded or raise an exception"""
if isinstance(bool_str, basestring) and bool_str:
if bool_str.lower() in ['true', 't', '1']: return True
elif bool_str.lower() in ['false', 'f', '0']: return False
#if here we couldn't parse it
raise ValueError("%s is no recognized as a boolean value" % bool_str)
结果是:
>>> [to_bool(v) for v in ['true','t','1','F','FALSE','0']]
[True, True, True, False, False, False]
>>> to_bool("")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in to_bool
ValueError: '' is no recognized as a boolean value
澄清一下,因为我的回答似乎冒犯了某人:
关键在于,您不希望只测试一个值,并假设另一个值。我不认为你总是想把所有东西都映射到未解析的值。这会产生容易出错的代码。
如果你知道你想要什么,就把它编码进去。
其他回答
def str2bool(str):
if isinstance(str, basestring) and str.lower() in ['0','false','no']:
return False
else:
return bool(str)
想法:检查你是否希望字符串被计算为False;否则bool()对于任何非空字符串返回True。
下面是我用来评估字符串真实性的东西:
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的结果大致相同,但更安全。
还有一种选择
from ansible.module_utils.parsing.convert_bool import boolean
boolean('no')
# False
boolean('yEs')
# True
boolean('true')
# True
我使用
# function
def to_bool(x):
return x in ("True", "true", True)
# test cases
[[x, to_bool(x)] for x in [True, "True", "true", False, "False", "false", None, 1, 0, -1, 123]]
"""
Result:
[[True, True],
['True', True],
['true', True],
[False, False],
['False', False],
['false', False],
[None, False],
[1, True],
[0, False],
[-1, False],
[123, False]]
"""
pydantic有一个优雅的解决方案:
import pydantic
>>> pydantic.parse_obj_as(bool, "true")
True