¿Convertir de una cadena a booleano en Python?


¿Alguien sabe cómo convertir de una cadena a un booleano en Python? He encontrado este enlace. Pero no parece una forma adecuada de hacerlo. Es decir, usando una funcionalidad incorporada, etc.

EDITAR:

La razón por la que pregunté esto es porque aprendí int("string"), de aquí. Intenté bool("string") pero siempre conseguí True.

>>> bool("False")
True
 487
Author: BMW, 2009-04-03

25 answers

Realmente, solo comparas la cadena con lo que esperas aceptar como que representa true, así que puedes hacer esto:

s == 'True'

O a verificaciones contra un montón de valores:

s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']

Tenga cuidado al usar lo siguiente:

>>> bool("foo")
True
>>> bool("")
False

Las cadenas vacías evalúan a False, pero todo lo demás evalúa a True. Por lo tanto, esto no debe usarse para ningún tipo de análisis.

 589
Author: Keith Gaughan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-28 02:16:14
def str2bool(v):
  return v.lower() in ("yes", "true", "t", "1")

Entonces llámalo así: {[12]]}

str2bool("yes")

> True

str2bool("no")

> False

str2bool("stuff")

> False

str2bool("1")

> True

str2bool("0")

> False


Manejando verdadero y falso explícitamente:

También puede hacer que su función compruebe explícitamente contra una lista Verdadera de palabras y una lista Falsa de palabras. Entonces, si está en ninguna de las dos listas, podría lanzar una excepción.

 207
Author: Brian R. Bondy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-14 18:44:10

Solo use:

distutils.util.strtobool(some_string)

Http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool

Los valores verdaderos son y, sí, t, verdadero, encendido y 1; los valores falsos son n, no, f, falso, apagado y 0. Aumenta ValueError si val es otra cosa.

 178
Author: jzwiener,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-27 17:42:22

Comenzando con Python 2.6, ahora hay 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.

Que parece funcionar, siempre y cuando estés seguro tus cadenas serán "True" o "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'

Normalmente no recomendaría esto, pero está completamente integrado y podría ser lo correcto dependiendo de sus requisitos.

 97
Author: Jacob Gabrielson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-28 18:06:39

El analizador sintáctico JSON también es útil para, en general, convertir cadenas a tipos python razonables.

>>> import json
>>> json.loads("false".lower())
False
>>> json.loads("True".lower())
True
 66
Author: Alan Marchiori,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-13 09:15:15

Esta versión mantiene la semántica de constructores como int(value) y proporciona una manera fácil de definir valores de cadena aceptables.

def to_bool(value):
    valid = {'true': True, 't': True, '1': True,
             'false': False, 'f': False, '0': False,
             }   

    if isinstance(value, bool):
        return value

    if not isinstance(value, basestring):
        raise ValueError('invalid literal for boolean. Not a string.')

    lower_value = value.lower()
    if lower_value in valid:
        return valid[lower_value]
    else:
        raise ValueError('invalid literal for boolean: "%s"' % value)


# Test cases
assert to_bool('true'), '"true" is True' 
assert to_bool('True'), '"True" is True' 
assert to_bool('TRue'), '"TRue" is True' 
assert to_bool('TRUE'), '"TRUE" is True' 
assert to_bool('T'), '"T" is True' 
assert to_bool('t'), '"t" is True' 
assert to_bool('1'), '"1" is True' 
assert to_bool(True), 'True is True' 
assert to_bool(u'true'), 'unicode "true" is True'

assert to_bool('false') is False, '"false" is False' 
assert to_bool('False') is False, '"False" is False' 
assert to_bool('FAlse') is False, '"FAlse" is False' 
assert to_bool('FALSE') is False, '"FALSE" is False' 
assert to_bool('F') is False, '"F" is False' 
assert to_bool('f') is False, '"f" is False' 
assert to_bool('0') is False, '"0" is False' 
assert to_bool(False) is False, 'False is False'
assert to_bool(u'false') is False, 'unicode "false" is False'

# Expect ValueError to be raised for invalid parameter...
try:
    to_bool('')
    to_bool(12)
    to_bool([])
    to_bool('yes')
    to_bool('FOObar')
except ValueError, e:
    pass
 14
Author: Michael Richmond,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-11 17:38:43

Aquí está mi versión. Comprueba con las listas de valores positivos y negativos, generando una excepción para los valores desconocidos. Y no recibe una cadena, pero cualquier tipo debe hacerlo.

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

Ejecuciones de muestra:

>>> 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
>>>
 12
Author: Petrucio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-17 18:57:43

Siempre podrías hacer algo como

myString = "false"
val = (myString == "true")

El bit en paréntesis evaluaría a False. Esta es solo otra forma de hacerlo sin tener que hacer una llamada a la función real.

 9
Author: helloandre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-04 06:16:09

No estoy de acuerdo con ninguna solución aquí, ya que son demasiado permisivas. Esto no es normalmente lo que quieres cuando analizas una cadena.

Así que aquí la solución que estoy usando:

def to_bool(bool_str):
    """Parse the string and return the boolean value encoded or raise an exception"""
    if isinstance(bool_str, basestring) and bool_str: 
        if bool_str.lower() in ['true', 't', '1']: return True
        elif bool_str.lower() in ['false', 'f', '0']: return False

    #if here we couldn't parse it
    raise ValueError("%s is no recognized as a boolean value" % bool_str)

Y los resultados:

>>> [to_bool(v) for v in ['true','t','1','F','FALSE','0']]
[True, True, True, False, False, False]
>>> to_bool("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in to_bool
ValueError: '' is no recognized as a boolean value

Solo para ser claro porque parece que mi respuesta ofendió a alguien de alguna manera:

El punto es que no desea probar solo un valor y asumir el otro. No creo que siempre quieras mapear Absolutamente todo al valor no analizado. Que produce código propenso a errores.

Entonces, si sabes lo que quieres codificarlo.

 7
Author: estani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-28 16:43:07

Simplemente puede usar la función integrada eval():

a='True'
if a is True:
    print 'a is True, a type is', type(a)
else:
    print "a isn't True, a type is", type(a)
b = eval(a)
if b is True:
    print 'b is True, b type is', type(b)
else:
    print "b isn't True, b type is", type(b)

Y la salida:

a isn't True, a type is <type 'str'>
b is True, b type is <type 'bool'>
 7
Author: lumartor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-11 11:27:49

Un truco genial y simple (basado en lo que @ Alan Marchiori publicó), pero usando yaml:

import yaml

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

Si esto es demasiado ancho, se puede refinar probando el resultado del tipo. Si el tipo devuelto por yaml es un str, entonces no se puede convertir a ningún otro tipo (que se me ocurra de todos modos), por lo que podría manejarlo por separado, o simplemente dejar que sea cierto.

No voy a hacer ninguna conjetura a la velocidad, pero ya que estoy trabajando con datos yaml bajo Qt gui de todos modos, esto tiene una buena simetría.

 6
Author: Rafe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-18 22:21:51

Probablemente ya tenga una solución, pero para otros que están buscando un método para convertir un valor a un valor booleano utilizando valores falsos "estándar" que incluyen None, [], {} y "" además de false, no y 0.

def toBoolean( val ):
    """ 
    Get the boolean value of the provided input.

        If the value is a boolean return the value.
        Otherwise check to see if the value is in 
        ["false", "f", "no", "n", "none", "0", "[]", "{}", "" ]
        and returns True if value is not in the list
    """

    if val is True or val is False:
        return val

    falseItems = ["false", "f", "no", "n", "none", "0", "[]", "{}", "" ]

    return not str( val ).strip().lower() in falseItems
 5
Author: Chris McMillan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-15 18:13:01

Un dict (en realidad, un defaultdict) te da una manera bastante fácil de hacer este truco:

from collections import defaultdict
bool_mapping = defaultdict(bool) # Will give you False for non-found values
for val in ['True', 'yes', ...]:
    bool_mapping[val] = True

print(bool_mapping['True']) # True
print(bool_mapping['kitten']) # False

Es muy fácil adaptar este método al comportamiento de conversión exacto que desee can puede llenarlo con valores Truth y Falsy permitidos y dejar que genere una excepción (o devuelva Ninguna) cuando no se encuentra un valor, o por defecto a True, o por defecto a False, o lo que desee.

 5
Author: Nate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-16 17:47:14

Esta es la versión que escribí. Combina varias de las otras soluciones en una sola.

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)

Si obtiene una cadena, espera valores específicos, de lo contrario genera una Excepción. Si no obtiene una cadena, simplemente deja que el constructor bool lo averigüe. Probado estos casos:

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),
    ]
 3
Author: Tom Ekberg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-14 17:07:45

Me gusta usar el operador ternario para esto, ya que es un poco más sucinto para algo que parece que no debería ser más de 1 línea.

True if myString=="True" else False
 3
Author: Clayton Rabenda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-01 13:07:39

La regla habitual para lanzar a un bool es que unos pocos literales especiales(False, 0, 0.0, (), [], {}) son falsas y luego todo lo demás es verdadero, por lo que recomiendo lo siguiente:

def boolify(val):
    if (isinstance(val, basestring) and bool(val)):
        return not val in ('False', '0', '0.0')
    else:
        return bool(val)
 3
Author: Carl G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-21 17:36:54

Me doy cuenta de que este es un post antiguo, pero algunas de las soluciones requieren bastante código, esto es lo que terminé usando:

def str2bool(value):
    return {"True": True, "true": True}.get(value, False)
 3
Author: Ron E,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-09 21:37:50

Si sabes que tu entrada será "Verdadera " o" Falsa " entonces por qué no usar:

def bool_convert(s):
    return s == "True"
 2
Author: Daniel van Flymen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-10 08:53:34

Si sabes que la cadena será "True" o "False", podrías usar eval(s).

>>> eval("True")
True
>>> eval("False")
False

Use esto solo si está seguro del contenido de la cadena, ya que lanzará una excepción si la cadena no contiene Python válido, y también ejecutará el código contenido en la cadena.

 1
Author: Joel Croteau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-22 21:34:16

Aquí hay un peludo, construido en forma de obtener muchas de las mismas respuestas. Tenga en cuenta que aunque python considera que "" es falso y todas las demás cadenas son verdaderas, TCL tiene una idea muy diferente sobre las cosas.

>>> 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 /']"
>>> 

Lo bueno de esto es que es bastante indulgente con los valores que puede usar. Es perezoso acerca de convertir cadenas en valores, y es higiénico acerca de lo que acepta y rechaza(tenga en cuenta que si la declaración anterior se dio en un aviso tcl, borraría los usuarios disco duro).

Lo malo es que requiere que Tkinter esté disponible, lo cual es generalmente, pero no universalmente cierto, y más significativamente, requiere que se cree una instancia de Tk, que es comparativamente pesada.

Lo que se considera verdadero o falso depende del comportamiento de la Tcl_GetBoolean, el cual considera 0, false, no y off falsa y 1, true, yes y on para ser verdad, insensible a mayúsculas y minúsculas. Cualquier otra cadena, incluida la vacía, causa una excepción.

 0
Author: SingleNegationElimination,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-11 21:31:45
def str2bool(str):
  if isinstance(str, basestring) and str.lower() in ['0','false','no']:
    return False
  else:
    return bool(str)

Idea: compruebe si desea que la cadena sea evaluada como False; de lo contrario bool() devuelve True para cualquier cadena no vacía.

 0
Author: xvga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-01 16:35:14

Aquí hay algo que junté para evaluar la veracidad de una cadena:

def as_bool(val):
 if val:
  try:
   if not int(val): val=False
  except: pass
  try:
   if val.lower()=="false": val=False
  except: pass
 return bool(val)

Más o menos los mismos resultados que el uso de eval pero más seguro.

 0
Author: tylerl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-29 08:09:54

Solo tenía que hacer esto... así que tal vez tarde a la fiesta - pero alguien puede encontrar útil

def str_to_bool(input, default):
    """
    | Default | not_default_str | input   | result
    | T       |  "false"        | "true"  |  T
    | T       |  "false"        | "false" |  F
    | F       |  "true"         | "true"  |  T
    | F       |  "true"         | "false" |  F

    """
    if default:
        not_default_str = "false"
    else:
        not_default_str = "true"

    if input.lower() == not_default_str:
        return not default
    else:
        return default
 0
Author: Rcynic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-03 01:03:09

Si usted tiene control sobre la entidad que regresar true/false, una opción es tener que volver 1/0 en lugar de true/false, entonces:

boolean_response = bool(int(response))

El cast extra a int maneja las respuestas de una red, que siempre son cadenas.

 0
Author: LXXIII,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-23 17:12:47

Usando la función incorporada de Python eval() y el método .capitalize(), puede convertir cualquier cadena "true" / "false" (independientemente de la mayúscula inicial) a un booleano verdadero de Python.

Por ejemplo:

true_false = "trUE"
type(true_false)

# OUTPUT: <type 'str'>

true_false = eval(true_false.capitalize())
type(true_false)

# OUTPUT: <type 'bool'>
 -4
Author: elPastor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-22 15:22:23