Friday, October 26, 2018
Converting from a string to boolean in Python?
Answer
Answer
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
Answer
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.
plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...
-
This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year. Unlike many other programm...
-
I’m trying to run the following command that reads JSON from a file and formats it with jq : jq -n -r --arg m $( It produces the des...
-
I am new to dask and I found so nice to have a module that makes it easy to get parallelization. I am working on a project where I was able ...
No comments:
Post a Comment