Converting a String to a Boolean in Python

April 8, 2008 at 1:11 am 13 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

About these ads

Entry filed under: CodeSnippet, Python, Tip. Tags: .

Simple Method to Search a Python List How Many Files in a Linux Directory

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

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

  • 11. fenix kredyty  |  June 15, 2013 at 12:04 am

    Spot on with this write-up, I honestly feel this site
    needs a great deal more attention. I’ll probably be back again to see more, thanks for the info!

  • […] 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, […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed



Follow

Get every new post delivered to your Inbox.

%d bloggers like this: