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 to False
.
Here's a MWE
of what I'm trying to do:
with open('file.dat', mode="r") as f:
for line in f:
reader = line.split()
# Convert to boolean <-- Not working?
flag = bool(reader[0])
if flag:
print 'flag == True'
else:
print 'flag == False'
The file.dat
file basically consists of a single string with the value True
or False
written inside. The arrangement looks very convoluted because this is a minimal example from a much larger code and this is how I read parameters into it.
Why is flag
always converting to True
?
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 could make it a "heroic"
ValueError
by doingraise ValueError("Cannot covert {} to a bool".format(s))
.Selecting this one since it uses no extra packages. Thanks guys!
What's wrong with "extra packages"? Are you referring to
ast
? It's part of the standard library, so it's not really extra.it might be a silly question but why does
bool
just not convert the stringsTrue
andFalse
to the boolean valuesTrue
andFalse
? Seems to be inconsistent behaviour from whatint
does. I just genuinely curious why my reasoning is wrong and why the other option was the decision.Whenever comparing strings I like to flatten the case, (where applicable). for example I would use: if s.upper() == 'TRUE': return True elif s.upper() == 'FALSE' return False