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

>>> bool("False")
True

当前回答

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

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

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

其他回答

def str2bool(str):
  if isinstance(str, basestring) and str.lower() in ['0','false','no']:
    return False
  else:
    return bool(str)

想法:检查你是否希望字符串被计算为False;否则bool()对于任何非空字符串返回True。

警告:此答案从Python 3.12起不再有效(从3.10起已弃用)

Use:

bool(distutils.util.strtobool(some_string))

Python 2: http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool Python >=3, <3.12: https://docs.python.org/3/distutils/apiref.html#distutils.util.strtobool Python >=3.12:由于PEP 632,不再是标准库的一部分

真值是y, yes, t, True, on和1;假值为n, no, f, False, off和0。如果val为其他值,则引发ValueError。

请注意,distutils.util. strtoool()返回整数表示,因此需要用bool()包装它以获得布尔值。

鉴于distutils将不再是标准库的一部分,下面是distutils.util. strtoool()的代码(请参阅源代码)。

def strtobool (val):
    """Convert a string representation of truth to true (1) or false (0).
    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
    'val' is anything else.
    """
    val = val.lower()
    if val in ('y', 'yes', 't', 'true', 'on', '1'):
        return 1
    elif val in ('n', 'no', 'f', 'false', 'off', '0'):
        return 0
    else:
        raise ValueError("invalid truth value %r" % (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 3.10版本中,你可以这样做;

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

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