如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
当前回答
在有限的情况或情况下,您可以对正在处理的数据做出强有力的假设。然而,由于自定义对象可以覆盖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.
其他回答
下面是我用来评估字符串真实性的东西:
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的结果大致相同,但更安全。
警告:此答案从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,))
使用这个解决方案:
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 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
>>>
你可以这样做
my_string = "false"
val = (my_string == "true")
parens中的位将计算为False。这是另一种不需要进行实际函数调用的方法。