如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
当前回答
dict(实际上是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和Falsy值填充它,并在没有找到值时让它引发异常(或返回None),或默认为True,或默认为False,或任何您想要的。
其他回答
这个答案使用了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)
# ...
dict(实际上是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和Falsy值填充它,并在没有找到值时让它引发异常(或返回None),或默认为True,或默认为False,或任何您想要的。
我知道这是一个老帖子,但一些解决方案需要相当多的代码,以下是我最终使用的:
def str2bool(value):
return {"True": True, "true": True}.get(value, False)
使用这个解决方案:
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.")
.blink { color: yellow; animation: blink-animation 0.5s infinite; } @keyframes blink-animation { 25% { background-color: black; color: cyan; } 50% { background-color: black; color: red; } 75% { background-color: black; color: lime; } } <h1 class="blink">WARNING: Do not use the following code unless you actually know what you are doing with it. Please read the attached disclaimers and make sure you trust your inputs as using this on untrusted inputs could destroy your data and/or cost you your job.</h1>
如果你知道字符串将是“True”或“False”,你可以使用eval(s)。
>>> eval("True")
True
>>> eval("False")
False
不过,只有在确定字符串的内容时才使用此方法,因为如果字符串不包含有效的Python,它将抛出异常,并且还将执行字符串中包含的代码。