如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
如何在Python中将字符串转换为布尔值?这个尝试返回True:
>>> bool("False")
True
当前回答
这是我写的版本。将其他几个解决方案合并为一个。
def to_bool(value):
"""
Converts 'something' to boolean. Raises exception if it gets a string it doesn't handle.
Case is ignored for strings. These string values are handled:
True: 'True', "1", "TRue", "yes", "y", "t"
False: "", "0", "faLse", "no", "n", "f"
Non-string values are passed to bool.
"""
if type(value) == type(''):
if value.lower() in ("yes", "y", "true", "t", "1"):
return True
if value.lower() in ("no", "n", "false", "f", "0", ""):
return False
raise Exception('Invalid value for boolean conversion: ' + value)
return bool(value)
如果它得到一个字符串,它期望特定的值,否则引发异常。如果它没有得到一个字符串,就让bool构造函数来计算它。测试这些案例:
test_cases = [
('true', True),
('t', True),
('yes', True),
('y', True),
('1', True),
('false', False),
('f', False),
('no', False),
('n', False),
('0', False),
('', False),
(1, True),
(0, False),
(1.0, True),
(0.0, False),
([], False),
({}, False),
((), False),
([1], True),
({1:2}, True),
((1,), True),
(None, False),
(object(), True),
]
其他回答
.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,它将抛出异常,并且还将执行字符串中包含的代码。
你也可以计算任何字符串字面值:
import ast
ast.literal_eval('True') # True
type(ast.literal_eval('True')) # <class 'bool'>
ls = '[1, 2, 3]'
ast.literal_eval(ls) # [1, 2, 3]
type(ast.literal_eval(ls)) # <class 'list'>
我必须这么做……所以,也许姗姗来迟——但有人可能会发现它很有用
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
该版本保留了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 str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
然后像这样称呼它:
>>> str2bool("yes")
True
>>> str2bool("no")
False
>>> str2bool("stuff")
False
>>> str2bool("1")
True
>>> str2bool("0")
False
显式处理true和false:
您还可以使函数显式地检查True单词列表和False单词列表。然后,如果它不在两个列表中,则可以抛出异常。