Convert True/False value read from file to boolean Convert True/False value read from file to boolean python python

Convert True/False value read from file to boolean


bool('True') and bool('False') always return True because strings 'True' and 'False' are not empty.

To quote a great man (and Python documentation):

5.1. Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].

All other values are considered true — so objects of many types are always true.

The built-in bool function uses the standard truth testing procedure. That's why you're always getting True.

To convert a string to boolean you need to do something like this:

def str_to_bool(s):    if s == 'True':         return True    elif s == 'False':         return False    else:         raise ValueError # evil ValueError that doesn't tell you what the wrong value was


you can use distutils.util.strtobool

>>> from distutils.util import strtobool>>> strtobool('True')1>>> strtobool('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.


Use ast.literal_eval:

>>> import ast>>> ast.literal_eval('True')True>>> ast.literal_eval('False')False

Why is flag always converting to True?

Non-empty strings are always True in Python.

Related: Truth Value Testing


If NumPy is an option, then:

>>> import StringIO>>> import numpy as np>>> s = 'True - False - True'>>> c = StringIO.StringIO(s)>>> np.genfromtxt(c, delimiter='-', autostrip=True, dtype=None) #or dtype=boolarray([ True, False,  True], dtype=bool)