在Python中如何将字符串转换为布尔值?以下尝试会返回 True
:
>>> bool("False")
True
def to_bool(value):
"""
Converts 'something' to boolean. Raises exception for invalid formats
Possible True values: 1, True, "1", "TRue", "yes", "y", "t"
Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ...
"""
if str(value).lower() in ("yes", "y", "true", "t", "1"): return True
if str(value).lower() in ("no", "n", "false", "f", "0", "0.0", "", "none", "[]", "{}"): return False
raise Exception('Invalid value for boolean conversion: ' + str(value))
样例运行结果:
>>> to_bool(True)
True
>>> to_bool("tRUe")
True
>>> to_bool("1")
True
>>> to_bool(1)
True
>>> to_bool(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: 2
>>> to_bool([])
False
>>> to_bool({})
False
>>> to_bool(None)
False
>>> to_bool("Wasssaaaaa")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: Wasssaaaaa
>>>
to_bool(["hello"])
,如果支持[]
的话,这应该是一个完全有效的调用。 - Rafael Tto_bool([])
。相反,他会做类似这样的事情:myList = someFunctionThatReturnAList
`if (is_bool(myList)):...´所以如果有一个列表并想知道这个列表是否为None或为空,则可以这样做。 - Rafael T- ThePracticalOnedef a2b(arg): ... default = bool(arg) ... if isinstance(arg, str): ... return arg.lower() in ['true', 't', 'yes', 'y', '1'] ... else: ... return default
if my_list:
而不是if to_bool(my_list):
。 我倾向于认为尝试支持list
和dict
可能是个坏主意。 除非我已经知道它是空的,否则我无法利用该支持,因为一个非空的会抛出错误,但是如果我已经知道了这一点,我甚至不需要这个功能。 其他的不对称性也有点靠不住。 字符串“'NONE'”被转换为False
(与正常的Python不一致),支持float 0.0
也具有与list
/ dict
相同的问题。 - jpmc26一个很酷的、简单的技巧(基于@Alan Marchiori发布的),但使用yaml:
import yaml
parsed = yaml.load("true")
print bool(parsed)
如果这太宽了,可以通过测试类型结果进行细化。 如果yaml返回的类型是字符串,则无法转换为任何其他类型(至少我能想到的),因此您可以单独处理它,或者让它保持不变。
我不会猜测速度,但既然我已经在Qt gui下使用yaml数据了,那么这就有了一个很好的对称性。
yaml.safe_load
而非yaml.load
。 - dreftymac开
和 关
。 - Laurenz字典(实际上是defaultdict)可以为您提供一种非常简单的方法来完成此技巧:
from collections import defaultdict
bool_mapping = defaultdict(bool) # Will give you False for non-found values
for val in ['True', 'yes', ...]:
bool_mapping[val] = True
print(bool_mapping['True']) # True
print(bool_mapping['kitten']) # False
如果您只想映射已知的值并在其他情况下抛出异常:
truthy_strings = ['True', 'yes'] # ... and so on
falsy_strings = ['False', 'no'] # ... and so on
bool_mapping = {}
for v in truthy_strings:
bool_mapping[v] = True
for v in falsy_strings:
bool_mapping[v] = False
如果你想聪明过头,可以使用 itertools
来缩短代码。
from itertools import chain, repeat
bool_mapping = dict(chain(zip(truthy_strings, repeat(True)), zip(falsy_strings, repeat(False))))
这可能很蠢,但itertools
技巧有点有趣。
我不同意这里的任何解决方法,因为它们太过宽松。当解析字符串时,这通常不是您想要的。
因此,这是我使用的解决方案:
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
为了明确一下,因为看起来我的回答似乎冒犯了某个人:
关键是你不想只测试一个值并假设另一个值。我认为你并不总是想将所有东西都映射到未解析的值。那样会产生容易出错的代码。
所以,如果你知道你想要什么,就把它编码进去。
elif
由于return
关键字是多余的,但它可以为您提供更多信息,而无需扫描return
。但这只是我的看法,如果存在PEP样式违规,我会进行更改。在没有其他限制的情况下,我们应该始终注重可读性(并且标准也是如此)。感谢您的提示和有趣的评论! - estani通过以下简单的逻辑,您可以将一个字符串(例如a = 'true'
或'false'
)转换为布尔值。
a = a.lower() == 'true'
a == 'true'
,那么这将设置 a=True
;如果 a == 'false'
,那么这将设置 a=False
。"truee"
转换为true。通常,如果输入无效,我们希望抛出异常。 - Neuronfrom 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]]
"""
你可能已经有了解决方案,但对于那些想要使用“标准”假值(包括None、[]、{}和"")以及false、no和0来将值转换为布尔值的人,以下是一种方法。
def toBoolean( val ):
"""
Get the boolean value of the provided input.
If the value is a boolean return the value.
Otherwise check to see if the value is in
["false", "f", "no", "n", "none", "0", "[]", "{}", "" ]
and returns True if value is not in the list
"""
if val is True or val is False:
return val
falseItems = ["false", "f", "no", "n", "none", "0", "[]", "{}", "" ]
return not str( val ).strip().lower() in falseItems
true
/false
的实体,一种选项是让它返回1
/0
而不是true
/false
,然后:
boolean_response = bool(int(response))
额外的int
转换处理来自网络的响应,这些响应始终为字符串。如果您知道输入要么是"True"
,要么是其他内容,那么为什么不使用以下代码:
def bool_convert(s):
return s == "True"
if s else False
这一部分。想想 "False" == "True"
已经会返回 False
了。 - Taylor D. Edmistonif type(s) is bool: return s
。 - kontur
bool("string")
时,它总是返回True
...除了空字符串bool("")
。 - FiddleStix