bool of any string is True unless the string is empty, i.e. bool(''). What exactly do you want to do? maybe there is a better way
Kloe R.
asked 05/16/18Converting from a string to boolean in Python?
Does 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, etc.
The reason I asked this is because I learned int("string"), from here. I tried bool("string") but always got True.
The reason I asked this is because I learned int("string"), from here. I tried bool("string") but always got True.
Follow
3
Add comment
More
Report
3 Answers By Expert Tutors
foo = 'True'
bar = foo.lower() == 'true'

Lane H. answered 05/16/18
Tutor
5
(17)
Software Developer who loves to help others
From my understanding you want to do this:
def getBoolValue(boolean_string):
if boolean_string.lower() == "false":
return False
elif boolean_string.lower()== "true":
return True
else:
return boolean_string # or whatever you want to return (exception?)
##usage##
bool_string = "True"
bool_string = getBoolValue(bool_string)
Like Arghavan A. said above bool() simply checks the string for emptiness which is why you get true for bool("False"). However I wouldn't advise creating the function above because string == 'True' is already really simple and I can't image you'll need to be doing to0 many checks like this
Still looking for help? Get the right answer, fast.
Ask a question for free
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Find an Online Tutor Now
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.