如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
当前回答
通过使用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'>
其他回答
该版本保留了int(value)等构造函数的语义,并提供了一种简单的方法来定义可接受的字符串值。
def to_bool(value):
valid = {'true': True, 't': True, '1': True,
'false': False, 'f': False, '0': False,
}
if isinstance(value, bool):
return value
if not isinstance(value, basestring):
raise ValueError('invalid literal for boolean. Not a string.')
lower_value = value.lower()
if lower_value in valid:
return valid[lower_value]
else:
raise ValueError('invalid literal for boolean: "%s"' % value)
# Test cases
assert to_bool('true'), '"true" is True'
assert to_bool('True'), '"True" is True'
assert to_bool('TRue'), '"TRue" is True'
assert to_bool('TRUE'), '"TRUE" is True'
assert to_bool('T'), '"T" is True'
assert to_bool('t'), '"t" is True'
assert to_bool('1'), '"1" is True'
assert to_bool(True), 'True is True'
assert to_bool(u'true'), 'unicode "true" is True'
assert to_bool('false') is False, '"false" is False'
assert to_bool('False') is False, '"False" is False'
assert to_bool('FAlse') is False, '"FAlse" is False'
assert to_bool('FALSE') is False, '"FALSE" is False'
assert to_bool('F') is False, '"F" is False'
assert to_bool('f') is False, '"f" is False'
assert to_bool('0') is False, '"0" is False'
assert to_bool(False) is False, 'False is False'
assert to_bool(u'false') is False, 'unicode "false" is False'
# Expect ValueError to be raised for invalid parameter...
try:
to_bool('')
to_bool(12)
to_bool([])
to_bool('yes')
to_bool('FOObar')
except ValueError, e:
pass
我必须这么做……所以,也许姗姗来迟——但有人可能会发现它很有用
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
这个答案使用了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)
# ...
下面是我用来评估字符串真实性的东西:
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的结果大致相同,但更安全。
这是我的版本。它同时检查正值和负值列表,对于未知值引发异常。它不接收字符串,但任何类型都可以。
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
>>>