Convert True / False read from file to boolean

I am reading the True - False value from the 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 line with the value True or False written inside. The layout looks very confusing because it is a minimal example from much larger code, and that is how I read the parameters in it.

Why is flag always converted to True ?

+65
python string boolean
Feb 12 '14 at 15:26
source share
13 answers

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

To quote a great man (and Python documentation ):

5.1. True Value Testing

Any object can be checked for truth, for use in an if or while condition, or as an operand of the following logical operations. The following values ​​are considered false:

  • ...
  • zero of any number 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 a standard truth-checking procedure. That is why you always become True .

To convert a string to a 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 
+77
Feb 12 '14 at 15:28
source share

Use ast.literal_eval :

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

Why is a flag always converted to True?

Non-empty strings are always True in Python.

Related: Credibility Check




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) 
+55
Feb 12 '14 at 15:28
source share

you can use distutils.util.strtobool

 >>> from distutils.util import strtobool >>> strtobool('True') 1 >>> strtobool('False') 0 

True values y , yes , t , True , on and 1 ; False values n , no , f , False , off and 0 . Raises a ValueError if val is something else.

+47
Feb 15 '16 at 14:46
source share

I do not suggest this as the best answer, just an alternative, but you can also do something like:

 flag = reader[0] == "True" 
Flag

True id reader [0] will be "True", otherwise it will be False .

+11
Feb 12 '14 at
source share

The cleanest solution I've seen:

 from distutils.util import strtobool def string_to_bool(string): return bool(strtobool(str(string))) 

Of course, this requires import, but it has the correct error handling and requires very little code to be written (and tested).

+8
Jan 12 '17 at 11:07 on
source share

Currently, it evaluates to True because the variable matters. Here is a good example of what happens when you evaluate arbitrary types as logical.

In short, you want to isolate the string 'True' or 'False' and run eval on it.

 >>> eval('True') True >>> eval('False') False 
+6
Jul 26 '16 at 5:45
source share

You can use dict to convert a string to boolean. Change this line flag = bool(reader[0]) to:

 flag = {'True': True, 'False': False}.get(reader[0], False) # default is False 
+5
Feb 12 '14 at 15:33
source share

If you want to be case insensitive, you can simply do:

 b = True if bool_str.lower() == 'true' else False 

Usage example:

 >>> bool_str = 'False' >>> b = True if bool_str.lower() == 'true' else False >>> b False >>> bool_str = 'true' >>> b = True if bool_str.lower() == 'true' else False >>> b True 
+1
Jun 12 '18 at 20:02
source share

You can do with json .

 In [124]: import json In [125]: json.loads('false') Out[125]: False In [126]: json.loads('true') Out[126]: True 
+1
Feb 14 '19 at 6:15
source share

pip install str2bool

 >>> from str2bool import str2bool >>> str2bool('Yes') True >>> str2bool('FaLsE') False 
0
Jul 24 '17 at 10:45
source share

If your data is from JSON, you can do it

import json

json.loads ('true')

truth

0
Jan 11 '19 at 22:05
source share

If you need a quick way to convert strings to bools (this works with most strings), give it a 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 
0
Feb 19 '19 at 12:17
source share

Just add that if your truth value can vary, for example, if it is input from different programming languages ​​or from different types, a more reliable method would be:

 flag = value in ['True','true',1,'T','t','1'] # this can be as long as you want to support 

And a more productive option would be (set lookup O (1)):

 TRUTHS = set(['True','true',1,'T','t','1']) flag = value in truths 
0
Apr 28 '19 at 10:20
source share



All Articles