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

>>> bool("False")
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.

其他回答

一个很酷,简单的技巧(基于@Alan Marchiori的帖子),但使用yaml:

import yaml

parsed = yaml.load("true")
print bool(parsed)

如果这个范围太广,可以通过测试类型结果进行细化。如果yaml返回的类型是str,那么它就不能转换为任何其他类型(我能想到的类型),所以可以单独处理它,或者让它为真。

我不会对速度做任何猜测,但因为我在Qt gui下使用yaml数据,这有一个很好的对称性。

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

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),
    ]

我使用

# function
def to_bool(x):
    return x in ("True", "true", True)

# test cases
[[x, to_bool(x)] for x in [True, "True", "true", False, "False", "false", None, 1, 0, -1, 123]]
"""
Result:
[[True, True],
 ['True', True],
 ['true', True],
 [False, False],
 ['False', False],
 ['false', False],
 [None, False],
 [1, True],
 [0, False],
 [-1, False],
 [123, False]]
"""

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

boolean = bool(int(response))

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

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

def str2bool(v):
  return v.lower() in ("yes", "true", "t", "1")

然后像这样称呼它:

>>> str2bool("yes")
True
>>> str2bool("no")
False
>>> str2bool("stuff")
False
>>> str2bool("1")
True
>>> str2bool("0")
False

显式处理true和false:

您还可以使函数显式地检查True单词列表和False单词列表。然后,如果它不在两个列表中,则可以抛出异常。