Converting from a string to boolean in Python
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping
--
Chapters
00:00 Converting From A String To Boolean In Python
00:14 Accepted Answer Score 1357
00:46 Answer 2 Score 558
02:01 Answer 3 Score 366
02:28 Answer 4 Score 196
02:42 Answer 5 Score 133
04:18 Thank you
--
Full question
https://stackoverflow.com/questions/7154...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #boolean
#avk47
ACCEPTED ANSWER
Score 1368
Really, you just compare the string to whatever you expect to accept as representing true, so you can do this:
s == 'True'
Or to checks against a whole bunch of values:
s.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
Be cautious when using the following:
>>> bool("foo")
True
>>> bool("")
False
Empty strings evaluate to False, but everything else evaluates to True. So this should not be used for any kind of parsing purposes.
ANSWER 2
Score 369
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
Then call it like so:
>>> str2bool("yes")
True
>>> str2bool("no")
False
>>> str2bool("stuff")
False
>>> str2bool("1")
True
>>> str2bool("0")
False
Handling true and false explicitly:
You could also make your function explicitly check against a True list of words and a False list of words. Then if it is in neither list, you could throw an exception.
ANSWER 3
Score 198
The JSON parser is also useful for in general converting strings to reasonable python types.
>>> import json
>>> json.loads("false".lower())
False
>>> json.loads("True".lower())
True
ANSWER 4
Score 134
Since Python 2.6 you can use ast.literal_eval, and it's still available in Python 3.
Evaluate an expression node or a string containing only a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans,
NoneandEllipsis.This can be used for evaluating strings containing Python values without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
This function had been documented as “safe” in the past without defining what that meant. That was misleading. This is specifically designed not to execute Python code, unlike the more general
eval(). There is no namespace, no name lookups, or ability to call out. But it is not free from attack: A relatively small input can lead to memory exhaustion or to C stack exhaustion, crashing the process. There is also the possibility for excessive CPU consumption denial of service on some inputs. Calling it on untrusted data is thus not recommended.
Which seems to work, as long as you're sure your strings are going to be either "True" or "False":
>>> ast.literal_eval("True")
True
>>> ast.literal_eval("False")
False
>>> ast.literal_eval("F")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
>>> ast.literal_eval("'False'")
'False'
I wouldn't normally recommend this, but it is completely built-in and could be the right thing depending on your requirements.