06 变量类型转换

117 阅读1分钟

转为整型 int

int()

str 转为 int型

image.png

float 转为int型

对于浮点数 转为 int型时 , 只会保留小数点前面的数值

image.png

boolean 转为 int型

true : 1 ; false : 0

image.png

转换失败的情况

image.png

转为浮点型 float

float()

int => float

image.png

str => float

image.png

转为字符串型 str

str()

int => str

image.png

float => str

image.png

boolean => str

image.png

转为布尔型 bool

bool()

int => bool

对于非0的整数(正数/负数) 转为 bool 都是 True

image.png

只有0是false

image.png

float => bool

正浮点数和负浮点数 转为 bool 都是 True

0.0 转为 bool 是 False

str => bool

只要 字符串中有内容 ,那么转换为bool时 就是 true

image.png

若字符串里面没有内容,则是 false

image.png

list => bool

只要列表中有数据,那么 强制类型转换为bool时 ,就是true

image.png

若列表中什么数据都没有,则是false

image.png

tuple => bool

只要元组中有数据,那么 强制类型转换为bool时,就是true

若元组中,什么数据都没有,则是false

dic => bool

字典中有数据,true

字典中没有数据 , false