Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
True vs False
#1
i am reading in data, splitting it, etc, and getting strings with 'True' and 'False', such as reading from python source code.
i want to convert these strings to boolean.  if they were decimal numbers i could use int() or float(), but bool() ...

Output:
Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> bool('True') True >>> bool('False') True >>>
... does not work that way.

so maybe i can do:

Output:
Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> 'False'=='True' False >>> 'True'=='True' True >>>
so far so good, but a bad string ...

Output:
Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> 'Maybe'=='True' False >>>
... does not do so well (an exception would be nice).  any pythonic suggestions?  converting 'true' and 'false' and 'TRUE' and 'FALSE' would be a plus.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
def str_to_bool(my_str):
    my_str = my_str.lower()
    return my_str in ('true', 'false') and my_str == 'true'

for s in ('True', 'False', 'true', 'false', 'Maybe', 'maybe'):
    print '{} -> {}'.format(s, str_to_bool(s))
Output:
True -> True False -> False true -> True false -> False Maybe -> False maybe -> False
or even

def str_to_bool(my_str):
    return my_str.lower() == 'true'

for s in ('True', 'False', 'true', 'false', 'Maybe', 'maybe'):
    print '{} -> {}'.format(s, str_to_bool(s))
Output:
True -> True False -> False true -> True false -> False Maybe -> False maybe -> False
Reply
#3
Sorry, I didn't read it right - you want exception for not valid boolean string

def str_to_bool(my_str):
    _my_str = my_str.lower()
    if not _my_str in ('true', 'false'):
        raise ValueError('{} has no boolean meaning'.format(my_str))
    return _my_str == 'true'

for s in ('True', 'False', 'true', 'false', 'Maybe', 'maybe'):
    try:
        print '{} -> {}'.format(s, str_to_bool(s))
    except ValueError as ve:
        print ve[0]
Output:
True -> True False -> False true -> True false -> False Maybe has no boolean meaning maybe has no boolean meaning
Reply
#4
I think this is the simplest way
def to_bool(text):
   booleans = {'true': True, 'false': False}
   return booleans[text.lower()]
Or maybe @burans code
def str_to_bool(my_str):
    return my_str.lower() == 'true'
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
yeah, 'Maybe' has no special meaning, yet
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#6
def to_bool(text):
    booleans = {'true': True, 'false': False}
    return booleans[text.lower()]
I like this one, only the exception in this case will be KeyError
Reply
#7
ok to shorten it a bit:

def to_bool(text):
   return {'true': True, 'false': False}[text.lower()]

or:

def to_bool(text):
  return {'true':True,'false':False,'yes':True,'no':False,'t':True,'f':False,'y':True,'n':False}[text.lower()]
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#8
(Jun-14-2017, 05:54 AM)buran Wrote:
def to_bool(text):
    booleans = {'true': True, 'false': False}
    return booleans[text.lower()]
I like this one, only the exception in this case will be KeyError

Hm!
It works here:
In [1]: def to_bool(text):
   ...:     booleans = {'true': True, 'false': False}
   ...:     return booleans[text.lower()]
   ...: 

In [2]: to_bool('True')
Out[2]: True

In [3]: to_bool('False')
Out[3]: False
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#9
(Jun-14-2017, 09:06 AM)wavic Wrote: Hm!
It works here:

I mean, the error that will be raised if text is not 'true' or 'false', but e.g. 'maybe'
It's ok to raise it, becasue that is what Skaperen wants. Just mention that it will be different than the one I raise in my code above
Reply
#10
Oh nice topik, had found a lot of usefull info! Thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  difference between «1 in [2] == False» and «(1 in [2]) == False» fbaldit 2 2,226 Apr-20-2020, 05:39 PM
Last Post: fbaldit
  Do break operators turn while loop conditions from True to False? Drone4four 5 2,947 Oct-24-2019, 07:11 PM
Last Post: newbieAuggie2019
  Returning True or False vs. True or None trevorkavanaugh 6 9,232 Apr-04-2019, 08:42 AM
Last Post: DeaD_EyE
  Returning true or false in a for loop bbop1232012 3 8,127 Nov-22-2018, 04:44 PM
Last Post: bbop1232012
  True == not False Skaperen 6 3,906 Aug-23-2018, 10:26 AM
Last Post: DeaD_EyE
  saving a true/false of a single value Skaperen 3 2,493 Aug-20-2018, 02:31 AM
Last Post: ichabod801
  Get True of false outside a loop morgandebray 2 2,449 Aug-09-2018, 12:39 PM
Last Post: morgandebray
  True or false if running something? Artdigy 4 3,407 Mar-27-2018, 05:50 PM
Last Post: nilamo
  How to turn variable true and false using function? hsunteik 5 6,486 Feb-20-2017, 11:44 AM
Last Post: hsunteik

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020