Converting from a string to boolean in Python?

Joan Venge picture Joan Venge · Apr 3, 2009 · Viewed 718.9k times · Source

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 built-in functionality, etc.

The reason I'm asking this is because I learned about int("string") from here. But when trying bool("string") it always returns True:

>>> bool("False")
True

Answer

Keith Gaughan picture Keith Gaughan · Apr 3, 2009

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.