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

>>> bool("False")
True

当前回答

您可能已经有了一个解决方案,但对于其他人来说,他们正在寻找一种方法,将值转换为布尔值,使用“标准”假值,包括None,[],{}和“”,除了false, no和0。

def toBoolean( val ):
    """ 
    Get the boolean value of the provided input.

        If the value is a boolean return the value.
        Otherwise check to see if the value is in 
        ["false", "f", "no", "n", "none", "0", "[]", "{}", "" ]
        and returns True if value is not in the list
    """

    if val is True or val is False:
        return val

    falseItems = ["false", "f", "no", "n", "none", "0", "[]", "{}", "" ]

    return not str( val ).strip().lower() in falseItems

其他回答

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

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

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

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

这里有一个复杂的,内置的方法来得到许多相同的答案。请注意,尽管python认为“”为假,所有其他字符串为真,但TCL对此有非常不同的想法。

>>> import Tkinter
>>> tk = Tkinter.Tk()
>>> var = Tkinter.BooleanVar(tk)
>>> var.set("false")
>>> var.get()
False
>>> var.set("1")
>>> var.get()
True
>>> var.set("[exec 'rm -r /']")
>>> var.get()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 324, in get
    return self._tk.getboolean(self._tk.globalgetvar(self._name))
_tkinter.TclError: 0expected boolean value but got "[exec 'rm -r /']"
>>> 

这样做的一个好处是,它对您可以使用的值是相当宽容的。它在将字符串转换为值方面很懒惰,在接受和拒绝什么方面很卫生(请注意,如果在tcl提示符下给出上述语句,它将删除用户的硬盘)。

不好的是,它要求Tkinter可用,这通常是正确的,但不是普遍的,更重要的是,需要创建Tk实例,这是相对繁重的。

什么是true或false取决于Tcl_GetBoolean的行为,它将0、false、no和off视为false,将1、true、yes和on视为true,不区分大小写。任何其他字符串,包括空字符串,都会导致异常。

转换为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)

在python 3.10版本中,你可以这样做;

def stringToBool(string: str) -> bool:
    match(string.lower()):
        case 'true':
            return True
        case 'false':
            return False

match-statement等价于c++中的switch。