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

>>> bool("False")
True

当前回答

使用str2bool包pip安装str2bool

其他回答

我还被要求将一个函数的输入更改为bool,主要输入在字符串中仅为True或False。所以,我只是这样编码:

def string_to_bool(s):
    bool_flag = True
    if s == "False":
        bool_flag = False
    elif s == "True":
        bool_flag = True
    else:
        print("Invalid Input")
    return bool_flag

你也可以检查它是否有更短的真假,如Y/N或Y/N等。

转换为bool类型的通常规则是,一些特殊的字面量(False, 0, 0.0,(),[],{})为假,然后其他的都为真,所以我推荐如下:

def boolify(val):
    if (isinstance(val, basestring) and bool(val)):
        return not val in ('False', '0', '0.0')
    else:
        return bool(val)

通过使用下面的简单逻辑,你可以将一个字符串转换为布尔值,比如a = 'true'或'false'。

a = a.lower() == 'true'

如果a= = 'true'则设置a= true,如果a= = 'false'则设置a= false。

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

从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'

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