Converting a String to a Boolean in Python

April 8, 2008

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

6 Comments Add your own

  • 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:

    def ParseBoolean (b):
    # Handle case where b is already a Boolean type.
    if b == False or b == True:
    return b
    b = b.strip()
    if len(b) < 1:
    raise ValueError (‘Cannot parse empty string into boolean.’)
    b = b[0].lower()
    if b == ‘t’ or b == ‘1′ or b == ‘y’:
    return True
    return False

  • 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())

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Categories

Archives

Top Posts