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

>>> bool("False")
True

当前回答

如果你可以控制返回true/false的实体,一种选择是让它返回1/0而不是true/false,那么:

boolean = bool(int(response))

额外的转换为int处理来自网络的响应,这些响应总是字符串。

2021年更新:“which are always string”——这是一个幼稚的观察。它取决于库使用的序列化协议。高级库(大多数web开发人员使用的库)的默认序列化通常是在序列化为字节之前转换为字符串。然后在另一边,它从字节反序列化为字符串,所以你丢失了任何类型信息。

其他回答

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

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

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

您可能已经有了一个解决方案,但对于其他人来说,他们正在寻找一种方法,将值转换为布尔值,使用“标准”假值,包括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

我还被要求将一个函数的输入更改为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等。

.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 3.10版本中,你可以这样做;

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

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