Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert True/False value read from file to boolean

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?

like image 225
Gabriel Avatar asked Feb 12 '14 15:02

Gabriel


People also ask

How do you convert a value to a boolean?

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.

How do you change a string from true to boolean true?

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".

How do you convert true to boolean true in Python?

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.


1 Answers

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 
like image 83
Nigel Tufnel Avatar answered Sep 22 '22 08:09

Nigel Tufnel