How to convert 'false' to 0 and 'true' to 1?

Viewed 336352

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

For example: x == 'true' and type(x) == unicode

I want x = 1

PS: I don’t want to use if-else.

9 Answers

+(False) converts to 0 and +(True) converts to 1

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

only with this:

const a = true; const b = false;

console.log(+a);//1 console.log(+b);//0

Related