如何在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'不区分大小写,如果是这样的话:
>>> x="TrUE"
>>> x.title() == 'True'
True
>>> x="false"
>>> x.title() == 'True'
False
还要注意,对于任何其他既不是真也不是假的输入,它将返回False
我必须这么做……所以,也许姗姗来迟——但有人可能会发现它很有用
def str_to_bool(input, default):
"""
| Default | not_default_str | input | result
| T | "false" | "true" | T
| T | "false" | "false" | F
| F | "true" | "true" | T
| F | "true" | "false" | F
"""
if default:
not_default_str = "false"
else:
not_default_str = "true"
if input.lower() == not_default_str:
return not default
else:
return default
这是我的版本。它同时检查正值和负值列表,对于未知值引发异常。它不接收字符串,但任何类型都可以。
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
>>>
通过使用Python内置的eval()函数和.capitalize()方法,您可以将任何“true”/“false”字符串(不管初始大写)转换为true Python布尔值。
例如:
true_false = "trUE"
type(true_false)
# OUTPUT: <type 'str'>
true_false = eval(true_false.capitalize())
type(true_false)
# OUTPUT: <type 'bool'>
在有限的情况或情况下,您可以对正在处理的数据做出强有力的假设。然而,由于自定义对象可以覆盖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.