如何在Python中将字符串转换为布尔值?这个尝试返回True:

>>> bool("False")
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,它将抛出异常,并且还将执行字符串中包含的代码。

其他回答

注意:如果eval()直接或间接接受用户的输入,请不要使用它,因为它很容易被滥用:

eval(“操作系统。系统(' rm -rf / ') ')

但干杯!研究还发现eval()并不是邪恶的,它完全可以用于可信代码。您可以使用它来将一个布尔字符串,如“False”和“True”转换为布尔类型。


我想分享我的简单解决方案:使用eval()。它将字符串True和False转换为适当的布尔类型,如果字符串的标题格式是True或False,总是第一个字母大写,否则该函数将引发一个错误。

e.g.

>>> eval('False')
False

>>> eval('True')
True

当然,对于动态变量,您可以简单地使用.title()来格式化布尔字符串。

>>> x = 'true'
>>> eval(x.title())
True

这将抛出一个错误。

>>> eval('true')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'true' is not defined

>>> eval('false')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'false' is not defined
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单词列表。然后,如果它不在两个列表中,则可以抛出异常。

使用str2bool包pip安装str2bool

一个很酷,简单的技巧(基于@Alan Marchiori的帖子),但使用yaml:

import yaml

parsed = yaml.load("true")
print bool(parsed)

如果这个范围太广,可以通过测试类型结果进行细化。如果yaml返回的类型是str,那么它就不能转换为任何其他类型(我能想到的类型),所以可以单独处理它,或者让它为真。

我不会对速度做任何猜测,但因为我在Qt gui下使用yaml数据,这有一个很好的对称性。

从Python 2.6开始,你可以使用ast.literal_eval:

>>> import ast
>>> help(ast.literal_eval)
Help on function literal_eval in module ast:

literal_eval(node_or_string)
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the following
    Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
    and None.

这似乎是可行的,只要你确定你的字符串将是“True”或“False”:

>>> ast.literal_eval("True")
True
>>> ast.literal_eval("False")
False
>>> ast.literal_eval("F")
Traceback (most recent call last):
  File "", line 1, in 
  File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
    return _convert(node_or_string)
  File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
    raise ValueError('malformed string')
ValueError: malformed string
>>> ast.literal_eval("'False'")
'False'

我通常不建议这样做,但它是完全内置的,可以根据您的需求来选择。