How to convert ‘false’ to 0 and ‘true’ to 1 in Python

后端 未结 9 1069
情歌与酒
情歌与酒 2021-01-29 22:55

Is there a way to convert true of type unicode to 1 and false of type unicode to 0 (in Python)?

For example: x

9条回答
  •  梦如初夏
    2021-01-29 23:05

    If you need a general purpose conversion from a string which per se is not a bool, you should better write a routine similar to the one depicted below. In keeping with the spirit of duck typing, I have not silently passed the error but converted it as appropriate for the current scenario.

    >>> def str2bool(st):
    try:
        return ['false', 'true'].index(st.lower())
    except (ValueError, AttributeError):
        raise ValueError('no Valid Conversion Possible')
    
    
    >>> str2bool('garbaze')
    
    Traceback (most recent call last):
      File "", line 1, in 
        str2bool('garbaze')
      File "", line 5, in str2bool
        raise TypeError('no Valid COnversion Possible')
    TypeError: no Valid Conversion Possible
    >>> str2bool('false')
    0
    >>> str2bool('True')
    1
    

提交回复
热议问题