Converting a String to a Boolean in Python
April 8, 2008 at 1:11 am 10 comments
Let’s say you have a string value that you want to convert to a boolean, but you’re not sure the format it will be in. Some languages have built-in functions for doing this, but to my knowledge Python doesn’t. Here’s a way to do it (though it’s not comprehensive). (Thanks to the commenter who helped me see a simpler way to do this.)
def parseBoolString(theString):
return theString[0].upper()==’T’
parseBoolString(“true”)
True
parseBoolString(“false”)
False
Entry filed under: CodeSnippet, Python, Tip. Tags: .
1. paddy3118 | April 8, 2008 at 10:46 pm
Hi,
It can be much more straight forward than that:
def parseBoolString(theString):
return theString == “T”
A string value of ‘T’ returns True and everything else, False.
- Paddy.
2. Noah | July 30, 2008 at 8:57 pm
If you are taking input from human config files then you might want to be more forgiving. I do it like this:
3. Noah | July 30, 2008 at 8:58 pm
Yeah, WordPress really sucks for pasting code examples.
4. diN0bot | August 28, 2008 at 12:42 pm
jumping off from where Noah landed:
def smart_bool(s):
if s is True or s is False:
return s
s = str(s).strip().lower()
return not s in ['false','f','n','0','']
I wanted to use types.BooleanType() for the first if predicate, but it doesn’t do what I expected.
I personally just wanted a way to turn ‘False’ into False (string to boolean).
5. Vishal | June 23, 2009 at 11:39 am
How about:
bDict = {‘false’:False, ‘true’:True}
x = ‘fAlsE’
return bDict[x.lower()]
The is 150 times faster than:
eval(x.capitalize())
when tested using timeit module.
6. Jan | October 12, 2009 at 2:40 pm
{“true”: True, “false”: False}.get(x.lower())
7. Junior Bernard | May 29, 2010 at 4:29 am
codecomments.wordpress.com’s done it once again! Superb writing!
8. Nathan Legakis | September 13, 2010 at 7:30 pm
Is there still not a function for this built-in to python?
9. feffe | October 13, 2010 at 9:50 am
bool(myString)
10. feffe | October 13, 2010 at 9:54 am
Does not work, sorry.
>>> bool(“foo”)
True
>>> bool(“”)
False
Empty strings are false, everything else is true.