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

后端 未结 9 1215
情歌与酒
情歌与酒 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

    Any of the following will work:

    s = "true"
    
    (s == 'true').real
    1
    
    (s == 'false').real
    0
    
    (s == 'true').conjugate()    
    1
    
    (s == '').conjugate()
    0
    
    (s == 'true').__int__()
    1
    
    (s == 'opal').__int__()    
    0
    
    
    def as_int(s):
        return (s == 'true').__int__()
    
    >>>> as_int('false')
    0
    >>>> as_int('true')
    1
    

提交回复
热议问题