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

>>> bool("False")
True

当前回答

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

其他回答

注意:如果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

我们可能需要捕捉'true'不区分大小写,如果是这样的话:

>>> x="TrUE"  
>>> x.title() == 'True'  
True  

>>> x="false"  
>>> x.title() == 'True'  
False  

还要注意,对于任何其他既不是真也不是假的输入,它将返回False

如果你知道你的输入将是“True”或其他什么,那么为什么不使用:

def bool_convert(s):
    return s == "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,))
def str2bool(str):
  if isinstance(str, basestring) and str.lower() in ['0','false','no']:
    return False
  else:
    return bool(str)

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