4

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(). Commented Nov 13, 2018 at 18:19
  • Can’t test because I’m on my phone, can you use eval()? Commented Nov 13, 2018 at 18:19
  • Look at @Austin's answer. Commented Nov 13, 2018 at 18:20
  • Why not simply use string == 'True'? Commented Nov 13, 2018 at 18:23

2 Answers 2

5

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'
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.