patternpythonCritical
Converting from a string to boolean in Python
Viewed 0 times
pythonconvertingbooleanstringfrom
Problem
How do I convert a string into a boolean in Python? This attempt returns
True:>>> bool("False")
TrueSolution
Really, you just compare the string to whatever you expect to accept as representing true, so you can do this:
Or to checks against a whole bunch of values:
Be cautious when using the following:
Empty strings evaluate to
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") # beware!
True
>>> bool("")
FalseEmpty strings evaluate to
False, but everything else evaluates to True. So this should not be used for any kind of parsing purposes.Code Snippets
s == 'True's.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']>>> bool("foo")
True
>>> bool("False") # beware!
True
>>> bool("")
FalseContext
Stack Overflow Q#715417, score: 1418
Revisions (0)
No revisions yet.