如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
当前回答
使用str2bool包pip安装str2bool
其他回答
实际上,你只是将字符串与你期望接受的表示true的字符串进行比较,所以你可以这样做:
s == 'True'
或者检查一大堆值:
s.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
使用以下物品时请谨慎:
>>> bool("foo")
True
>>> bool("")
False
空字符串的值是False,但其他的值都是True。所以这个不应该用于任何解析目的。
通过使用下面的简单逻辑,你可以将一个字符串转换为布尔值,比如a = 'true'或'false'。
a = a.lower() == 'true'
如果a= = 'true'则设置a= true,如果a= = 'false'则设置a= false。
pydantic有一个优雅的解决方案:
import pydantic
>>> pydantic.parse_obj_as(bool, "true")
True
这个答案使用了Django Rest Framework (DRF) 3.14中的代码。
你可以:
from rest_framework.fields import BooleanField
f = BooleanField(allow_null=True)
test_values = [ True, "True", "1", 1, -1, 1.0, "true", "t", "on",
None, "null", "NULL",
False, "False", "0", 0, "false", "f", 0.0, "off" ]
for item in test_values:
r = f.to_internal_value(item)
print(r)
# a shorter version
from rest_framework.fields import BooleanField
test_values = [ True, "True", "1", 1, -1, 1.0, "true", "t", "on",
None, "null", "NULL",
False, "False", "0", 0, "false", "f", 0.0, "off" ]
for item in test_values:
print(BooleanField(allow_null=True).to_internal_value(item))
或者您可以调整BooleanField的代码,使其适合您的需要。下面是DRF 3.x中类BooleanField的实际代码
# from rest_framework.fields
# ...
class BooleanField(Field):
default_error_messages = {
'invalid': _('Must be a valid boolean.')
}
default_empty_html = False
initial = False
TRUE_VALUES = {
't', 'T',
'y', 'Y', 'yes', 'Yes', 'YES',
'true', 'True', 'TRUE',
'on', 'On', 'ON',
'1', 1,
True
}
FALSE_VALUES = {
'f', 'F',
'n', 'N', 'no', 'No', 'NO',
'false', 'False', 'FALSE',
'off', 'Off', 'OFF',
'0', 0, 0.0,
False
}
NULL_VALUES = {'null', 'Null', 'NULL', '', None}
def to_internal_value(self, data):
try:
if data in self.TRUE_VALUES:
return True
elif data in self.FALSE_VALUES:
return False
elif data in self.NULL_VALUES and self.allow_null:
return None
except TypeError: # Input is an unhashable type
pass
self.fail('invalid', input=data)
def to_representation(self, value):
if value in self.TRUE_VALUES:
return True
elif value in self.FALSE_VALUES:
return False
if value in self.NULL_VALUES and self.allow_null:
return None
return bool(value)
# ...
您可能已经有了一个解决方案,但对于其他人来说,他们正在寻找一种方法,将值转换为布尔值,使用“标准”假值,包括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