2

Is there a way in python to parse the string 'True' as True (boolean) and 'False' as False (boolean)?

I know I could do bool('True') or bool('False') but each would be True

NewToJS
  • 2,011
  • 4
  • 35
  • 62

2 Answers2

4

Use ast.literal_eval:

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

If you do type(ast.literal_eval('False')), you see <class 'bool'>:

>>> type(ast.literal_eval('False'))
<class 'bool'>

You could also write your own function that returns 'True' as boolean True, 'False' as boolean False and if you supply any other input, it returns the same back:

def parse(string):
    d = {'True': True, 'False': False}
    return d.get(string, string)

Now, you call as:

>>> parse('True')
True
>>> parse('False')
False
>>> parse('Anything')
'Anything'
Austin
  • 25,759
  • 4
  • 25
  • 48
2

In this case I would not recommend ast.literal_eval or eval. The best thing to do is probably this:

def parse_boolean(b):
    return b == "True"

"True" will return True and "False" will return False.

sam-pyt
  • 1,027
  • 15
  • 26