Convert True/False value read from file to boolean

前端 未结 14 870

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

    you can use distutils.util.strtobool

    >>> from distutils.util import strtobool
    
    >>> strtobool('True')
    1
    >>> strtobool('False')
    0
    

    True values are y, yes, t, true, on and 1; False values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

    0 讨论(0)
  • 2020-12-07 18:50

    If you want to be case-insensitive, you can just do:

    b = True if bool_str.lower() == 'true' else False
    

    Example usage:

    >>> bool_str = 'False'
    >>> b = True if bool_str.lower() == 'true' else False
    >>> b
    False
    >>> bool_str = 'true'
    >>> b = True if bool_str.lower() == 'true' else False
    >>> b
    True
    
    0 讨论(0)
  • 2020-12-07 18:51

    Using dicts to convert "True" in True:

    def str_to_bool(s: str):
        status = {"True": True,
                    "False": False}
        try:
            return status[s]
        except KeyError as e:
            #logging
    
    0 讨论(0)
  • 2020-12-07 18:52

    You can use dict to convert string to boolean. Change this line flag = bool(reader[0]) to:

    flag = {'True': True, 'False': False}.get(reader[0], False) # default is False
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-07 18:58

    pip install str2bool

    >>> from str2bool import str2bool
    >>> str2bool('Yes')
    True
    >>> str2bool('FaLsE')
    False
    
    0 讨论(0)
提交回复
热议问题