Convert True/False value read from file to boolean

前端 未结 14 933

I\'m reading a True - False value from a file and I need to convert it to boolean. Currently it always converts it to True even if the value is set

14条回答
  •  青春惊慌失措
    2020-12-07 18:54

    The cleanest solution that I've seen is:

    from distutils.util import strtobool
    def string_to_bool(string):
        return bool(strtobool(str(string)))
    

    Sure, it requires an import, but it has proper error handling and requires very little code to be written (and tested).

提交回复
热议问题