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

>>> bool("False")
True

当前回答

从Python 2.6开始,你可以使用ast.literal_eval:

>>> import ast
>>> help(ast.literal_eval)
Help on function literal_eval in module ast:

literal_eval(node_or_string)
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the following
    Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
    and None.

这似乎是可行的,只要你确定你的字符串将是“True”或“False”:

>>> ast.literal_eval("True")
True
>>> ast.literal_eval("False")
False
>>> ast.literal_eval("F")
Traceback (most recent call last):
  File "", line 1, in 
  File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
    return _convert(node_or_string)
  File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
    raise ValueError('malformed string')
ValueError: malformed string
>>> ast.literal_eval("'False'")
'False'

我通常不建议这样做,但它是完全内置的,可以根据您的需求来选择。

其他回答

JSON解析器在将字符串转换为合理的python类型时也很有用。

>>> import json
>>> json.loads("false".lower())
False
>>> json.loads("True".lower())
True

使用str2bool包pip安装str2bool

我喜欢使用三元运算符,因为它对于不应该超过一行的东西来说更简洁一些。

True if my_string=="True" else False

这是我的版本。它同时检查正值和负值列表,对于未知值引发异常。它不接收字符串,但任何类型都可以。

def to_bool(value):
    """
       Converts 'something' to boolean. Raises exception for invalid formats
           Possible True  values: 1, True, "1", "TRue", "yes", "y", "t"
           Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ...
    """
    if str(value).lower() in ("yes", "y", "true",  "t", "1"): return True
    if str(value).lower() in ("no",  "n", "false", "f", "0", "0.0", "", "none", "[]", "{}"): return False
    raise Exception('Invalid value for boolean conversion: ' + str(value))

示例:

>>> to_bool(True)
True
>>> to_bool("tRUe")
True
>>> to_bool("1")
True
>>> to_bool(1)
True
>>> to_bool(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: 2
>>> to_bool([])
False
>>> to_bool({})
False
>>> to_bool(None)
False
>>> to_bool("Wasssaaaaa")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: Wasssaaaaa
>>>

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