Converting From A String To Boolean In Python?


Answer :

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.



Use:



bool(distutils.util.strtobool(some_string))



  • Python 2: http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool

  • Python 3: https://docs.python.org/3/distutils/apiref.html#distutils.util.strtobool




True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.




Be aware that distutils.util.strtobool() returns integer representations and thus it needs to be wrapped with bool() to get Boolean values.



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.



Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable