如何在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
澄清一下,因为我的回答似乎冒犯了某人:
关键在于,您不希望只测试一个值,并假设另一个值。我不认为你总是想把所有东西都映射到未解析的值。这会产生容易出错的代码。
如果你知道你想要什么,就把它编码进去。
其他回答
我喜欢使用三元运算符,因为它对于不应该超过一行的东西来说更简洁一些。
True if my_string=="True" else False
如果你知道你的输入将是“True”或其他什么,那么为什么不使用:
def bool_convert(s):
return s == "True"
我知道这是一个老帖子,但一些解决方案需要相当多的代码,以下是我最终使用的:
def str2bool(value):
return {"True": True, "true": True}.get(value, False)
警告:此答案从Python 3.12起不再有效(从3.10起已弃用)
Use:
bool(distutils.util.strtobool(some_string))
Python 2: http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool Python >=3, <3.12: https://docs.python.org/3/distutils/apiref.html#distutils.util.strtobool Python >=3.12:由于PEP 632,不再是标准库的一部分
真值是y, yes, t, True, on和1;假值为n, no, f, False, off和0。如果val为其他值,则引发ValueError。
请注意,distutils.util. strtoool()返回整数表示,因此需要用bool()包装它以获得布尔值。
鉴于distutils将不再是标准库的一部分,下面是distutils.util. strtoool()的代码(请参阅源代码)。
def strtobool (val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0
else:
raise ValueError("invalid truth value %r" % (val,))
我使用
# 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]]
"""