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

>>> bool("False")
True

当前回答

我知道这是一个老帖子,但一些解决方案需要相当多的代码,以下是我最终使用的:

def str2bool(value):
    return {"True": True, "true": True}.get(value, False)

其他回答

警告:此答案从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,))

你也可以计算任何字符串字面值:

import ast
ast.literal_eval('True')  # True
type(ast.literal_eval('True'))  # <class 'bool'>


ls = '[1, 2, 3]'
ast.literal_eval(ls)  # [1, 2, 3]
type(ast.literal_eval(ls))  # <class 'list'>

这里有一个复杂的,内置的方法来得到许多相同的答案。请注意,尽管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,不区分大小写。任何其他字符串,包括空字符串,都会导致异常。

这是我写的版本。将其他几个解决方案合并为一个。

def to_bool(value):
    """
    Converts 'something' to boolean. Raises exception if it gets a string it doesn't handle.
    Case is ignored for strings. These string values are handled:
      True: 'True', "1", "TRue", "yes", "y", "t"
      False: "", "0", "faLse", "no", "n", "f"
    Non-string values are passed to bool.
    """
    if type(value) == type(''):
        if value.lower() in ("yes", "y", "true",  "t", "1"):
            return True
        if value.lower() in ("no",  "n", "false", "f", "0", ""):
            return False
        raise Exception('Invalid value for boolean conversion: ' + value)
    return bool(value)

如果它得到一个字符串,它期望特定的值,否则引发异常。如果它没有得到一个字符串,就让bool构造函数来计算它。测试这些案例:

test_cases = [
    ('true', True),
    ('t', True),
    ('yes', True),
    ('y', True),
    ('1', True),
    ('false', False),
    ('f', False),
    ('no', False),
    ('n', False),
    ('0', False),
    ('', False),
    (1, True),
    (0, False),
    (1.0, True),
    (0.0, False),
    ([], False),
    ({}, False),
    ((), False),
    ([1], True),
    ({1:2}, True),
    ((1,), True),
    (None, False),
    (object(), True),
    ]

在有限的情况或情况下,您可以对正在处理的数据做出强有力的假设。然而,由于自定义对象可以覆盖Python中的__eq__相等性检查,因此存在一个重要的陷阱。看看下面这个刻意简化的玩具例子:

In [1]: class MyString: 
   ...:     def __init__(self, value): 
   ...:         self.value = value 
   ...:     def __eq__ (self, obj): 
   ...:         if hasattr(obj, 'value'): 
   ...:             return obj.value == self.value 
   ...:         return False 
   ...:                                                                                                                                           

In [2]: v = MyString("True")                                                                                                                      

In [3]: v == "True"                                                                                                                               
Out[3]: False

如果你想象有人继承了MyString的字符串类型,或者实现了各种原生字符串方法,repr等,这样MyString实例的行为就和字符串完全一样,但是在相等性检查中有特殊的额外值步骤,那么简单地使用== 'True'将会失败,而且从用户的角度来看,这很可能是一个无声的失败。

这就是为什么将type强制转换为您想要执行的相等性检查的确切性质,将其封装到一个helper函数中,并对依赖这种“已注册”的方式进行验证是一种很好的实践。例如,在MyString中,你可以这样写,

def validate(s):
    if isinstance(s, str):
        return s == 'True'
    elif isinstance(s, MyString):
        return s.value == 'True' # <-- business logic
    ...
    raise ValueError(f"Type {type(s)} not supported for validation.")

或者另一种常用的模式是反向透视图,其中您只为验证定义了一种行为,但是您有一个helper函数,它将强制转换为适合于该单一验证行为的类型,例如

def to_str(s):
    if isinstance(s, str):
        return s
    elif isinstance(s, MyString):
        return s.value
    ...
    raise ValueError(f"Unsupported type {type(s)}")

def validate(s):
    return to_str(s) == 'True'
    

It might look like we're adding a lot of boilerplate and verbosity. We could glibly express critique by saying, "why write all that if you can just write s == 'True'?" - But it misses the point that when you are validating something, you need to make sure all of your preconditions hold for the validation logic to be applied. If you can assume some data is a plain str type and you don't need to do any of that precondition (such as type) checking, great - but that's a very rare situation and it can be misleading to characterize the general situation for this question as being amenable to one super short and concise equality check.