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

4
  • Take a look at ast.literal_eval().
    – Vasilis G.
    Nov 13, 2018 at 18:19
  • Can’t test because I’m on my phone, can you use eval()?
    – amitchone
    Nov 13, 2018 at 18:19
  • Look at @Austin's answer.
    – Vasilis G.
    Nov 13, 2018 at 18:20
  • Why not simply use string == 'True'?
    – Jongware
    Nov 13, 2018 at 18:23

2 Answers 2

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

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.