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
?
The Boolean() Function Boolean() is a global function that converts the value it's passed into a boolean. You shouldn't use this with the new keyword ( new Boolean ) as this creates an instance of a Boolean that has a type of object. Below is an example of the correct use of this function.
To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
Given a string list, convert the string truth values to Boolean values using Python. Input : test_list = ["True", "False", "True", "False"] Output : [True, False, True, False] Explanation : String booleans converted to actual 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With