Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 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 built-in functionality, etc.

The reason I'm asking this is because I learned about int("string") from here. But when trying bool("string") it always returns True:

>>> bool("False") True 
like image 611
Joan Venge Avatar asked Apr 03 '09 19:04

Joan Venge


People also ask

How do I convert string to boolean?

To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

How do you convert true to boolean true in Python?

Given a string list, convert the string truth values to Boolean values using Python. Input : test_list = ["True", "False", "True", "False"] Output : [True, False, True, False] Explanation : String booleans converted to actual Boolean.

How do you convert a value to a boolean?

We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e “true” or “false”.

How do you change an object to a boolean in Python?

You can convert True and False to strings 'True' and 'False' with str() . Non-empty strings are considered True , so if you convert False to strings with str() and then back to bool type with bool() , it will be True .


1 Answers

Really, you just compare the string to whatever you expect to accept as representing true, so you can do this:

s == 'True' 

Or to checks against a whole bunch of values:

s.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh'] 

Be cautious when using the following:

>>> bool("foo") True >>> bool("") False 

Empty strings evaluate to False, but everything else evaluates to True. So this should not be used for any kind of parsing purposes.

like image 120
Keith Gaughan Avatar answered Sep 23 '22 02:09

Keith Gaughan