Converting from a string to boolean in Python?


Question

Does anyone know how to do convert from a string to a boolean in Python? I found this link. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.

EDIT:

The reason I asked this is because I learned int("string"), from here. I tried bool("string") but always got True.

>>> bool("False")
True
1
616
5/4/2017 12:39:09 PM

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

706
2/28/2012 2:16:14 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon