Is there a boolean(somestring) equivalent of int(somestring). bool('false') -> True

Vineet Jain vineet at eswap.com
Sun Apr 11 23:06:29 EDT 2004


a few small changes to your code to handle booleans passed in and convert
everython to lower case:

true_values = '1 yes true on'.split()
false_values = '0 no false off'.split()
def parse_boolean_value(s):
    if type(s) == bool: return s
    if type(s) == string: s = s.lower()
    if s in true_values: return True
    if s in false_values: return False
    raise ValueError



-----Original Message-----
From: Jeff Epler [mailto:jepler at unpythonic.net]
Sent: Sunday, April 11, 2004 5:35 PM
To: Vineet Jain
Cc: python-list at python.org
Subject: Re: Is there a boolean(somestring) equivalent of
int(somestring). bool('false') -> True


The reason that
>>> bool('false')
returns True is the same reason that
>>> not 'false'
is False:  A non-empty string, when treated as a boolean, is true.

Changing the meaning of bool() is not likely to happen.

Here's one piece of code you might try to get the behavior you desire:

true_values = '1 yes true on'.split()
false_values = '0 no false off'.split()
def parse_boolean_value(s):
    if s in true_values: return True
    if s in false_values: return False
    raise ValueError

'i in seq' is just like checking whether any item in seq is equal to i.
If seq is a dictionary or a set (or defines __contains__), this test can
be a little more efficient, but the efficiency is unlikely to matter
when there are only 4 items.

Jeff





More information about the Python-list mailing list