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