Convert True/False value read from file to boolean

前端 未结 14 936

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:42

    bool('True') and bool('False') always return True because strings 'True' and 'False' are not empty.

    To quote a great man (and Python documentation):

    5.1. Truth Value Testing

    Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

    • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
    • any empty sequence, for example, '', (), [].

    All other values are considered true — so objects of many types are always true.

    The built-in bool function uses the standard truth testing procedure. That's why you're always getting True.

    To convert a string to boolean you need to do something like this:

    def str_to_bool(s):
        if s == 'True':
             return True
        elif s == 'False':
             return False
        else:
             raise ValueError # evil ValueError that doesn't tell you what the wrong value was
    

提交回复
热议问题