I\'m reading a True - False
value from a file and I need to convert it to boolean. Currently it always converts it to True
even if the value is set
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=bool
array([ True, False, True], dtype=bool)
Currently, it is evaluating to True
because the variable has a value. There is a good example found here of what happens when you evaluate arbitrary types as a boolean.
In short, what you want to do is isolate the 'True'
or 'False'
string and run eval
on it.
>>> eval('True')
True
>>> eval('False')
False
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
I'm not suggested this as the best answer, just an alternative but you can also do something like:
flag = reader[0] == "True"
flag will be True
id reader[0] is "True", otherwise it will be False
.
If you need quick way to convert strings into bools (that functions with most strings) try.
def conv2bool(arg):
try:
res= (arg[0].upper()) == "T"
except Exception,e:
res= False
return res # or do some more processing with arg if res is false
If your data is from json, you can do that
import json
json.loads('true')
True