如何在Python中将“假"转换为0,将“真"转换为1 [英] How to convert ‘false’ to 0 and ‘true’ to 1 in Python

查看:319
本文介绍了如何在Python中将“假"转换为0,将“真"转换为1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将类型unicodetrue转换为1并将类型unicodefalse转换为0(在Python中)?

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

例如:x == 'true' and type(x) == unicode

我想要x = 1

PS:我不想使用if-else.

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

推荐答案

在布尔测试中使用int():

x = int(x == 'true')

int()将布尔值转换为10.请注意,任何等于'true'的值都将导致返回0.

int() turns the boolean into 1 or 0. Note that any value not equal to 'true' will result in 0 being returned.

这篇关于如何在Python中将“假"转换为0,将“真"转换为1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆