Coder Perfect

In Python, how do I convert a string to a boolean?

Problem

Is anyone familiar with how to convert a string to a boolean in Python? This is where I came across this link. However, it does not appear to be a valid method of doing so. Using built-in capabilities, for example.

I’m asking since this is where I learned about int(“string”) from. When you attempt bool(“string”), however, it always returns True:

>>> bool("False")
True

Asked by Joan Venge

Solution #1

Really, all you have to do is compare the string to anything you expect to accept as true, so you can do something like this:

s == 'True'

Alternatively, you can check against a large number of values:

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

When utilizing the following, use caution:

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

The value of empty strings is False, but the value of all other strings is True. As a result, this should not be utilised for any sort of parsing.

Answered by Keith Gaughan

Solution #2

Use:

bool(distutils.util.strtobool(some_string))

Be aware that distutils.util.strtobool() returns integer representations and thus it needs to be wrapped with bool() to get Boolean values.

Answered by jzwiener

Solution #3

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

Then call it like so:

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

Explicitly handling true and false:

You may alternatively make your function verify against a True and a False list of words directly. You might then throw an exception if it isn’t in either list.

Answered by Brian R. Bondy

Solution #4

The JSON parser can also be used to convert text to Python types in general.

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

Answered by Alan Marchiori

Solution #5

As of Python 2.6, there is a new function called 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.

Which appears to work as long as you’re certain your strings will be “True” or “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'

I wouldn’t generally propose this, but it is built-in and may be the best option for you based on your needs.

Answered by Jacob Gabrielson

Post is based on https://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python