Converting from a string to boolean in Python?

647    Asked by PeterWilkins in Python , Asked on Apr 2, 2021

Does anyone know how to do the conversion from a string to a boolean in Python?

The reason I asked this is because I learned int("string"), from here. I tried bool("string") but always got True.

>>> bool("False") 

True

Answered by Peter Wilkins

If you are facing string to boolean python error in your coding then you can use the following way to get the desired output:-

def str2bool(v):
   return str(v).lower() in ("yes", "true", "t", "1")
str2bool("no")

Your Answer

Interviews

Parent Categories