在Python中数字类型数据如何转换


Number类型的强制转换

int强制将数据转换成字符串

可转换类型:int、float、bool、纯数字字符串

var = 10
res = int(var)
print(res, type(res))

var = 3.14
res = int(var)
print(res, type(res))

var  = True
res = int(var)
print(res, type(res))

var = False
res = int(var)
print(res, type(res))

var = "123456"
res = int(var)
print(res, type(res))

# var = "123abc"
# res = int(var)
# print(res, type(res))      # Error

# var = 3+5j
# res = int(var)
# print(res, type(res))      # Error

float强制将数据转换成字符串

可转换类型:int、float、bool、纯数字字符串、纯小数字符串

var = 10
res = float(var)
print(res, type(res))

var = 3.14
res = float(var)
print(res, type(res))

var  = True
res = float(var)
print(res, type(res))

var = False
res = float(var)
print(res, type(res))

var = "123456"
res = float(var)
print(res, type(res))

var = "0.123"
res = float(var)
print(res, type(res))

# var = "123abc"
# res = float(var)
# print(res, type(res))      # Error

# var = 3+5j
# res = float(var)
# print(res, type(res))      # Error

complex强制将数据转换成字符串

可转换类型:int、float、bool、complex、纯数字字符串、纯复数字符串

var = 10
res = complex(var)
print(res, type(res))

var = 3.14
res = complex(var)
print(res, type(res))

var  = True
res = complex(var)
print(res, type(res))

var = False
res = complex(var)
print(res, type(res))

var = "123456"
res = complex(var)
print(res, type(res))

var = "5+2j"
res = complex(var)
print(res, type(res))

var = 3+5j
res = complex(var)
print(res, type(res))

# var = "123abc"
# res = complex(var)
# print(res, type(res))      # Error

bool强制将数据转换成字符串

可转换强转一切数据类型,返回值为True或False

var = 3+5j
res = bool(var)
print(res, type(res))

var = "123abc"
res = bool(var)
print(res, type(res))

var = [1, 2, 3,"abc"]
res = bool(var)
print(res, type(res))

var = (1, 2, 3,"abc")
res = bool(var)
print(res, type(res))

var = {1, 2, 3,"abc"}
res = bool(var)
print(res, type(res))

var = {"a":1, "b":2}
res = bool(var)
print(res, type(res))

bool值为False的十种情况

0      # 整型0
0.0    # 浮点型0.0
False  # 布尔型False
0j     # 复数型0j或0+0j
""     # 空字符串
[]     # 空列表
()     # 空元组
set()  # 空集合
{}     # 空字典
None   # 空

扩展

强转空数据时,默认转换成当前数据类型的一个值

res = int() 
# 结果:0 <class 'int'>
print(res, type(res))

Number自动类型转换

默认低精度向高精度进行转换:bool -> int -> float -> complex

# bool + float
res = True  + 344.565 
# 1.0 + 344.565 = 345.565
print(res ,type(res)) 

# int + float
res = 5 + 7.88 
# 5.0 + 7.88 = 12.88
print(res ,type(res)) 

# float + complex 
res = 5.66 + 9.1 -90j 
# (5.66+0j) + (9.1-90j) = 14.76-90j
print(res ,type(res))

小数存在精度损耗问题,小数后面一般有时截取15~18位,但是不绝对

在Python中数字类型数据如何转换介绍到这里,更多Python学习请参考编程字典Python教程 和问答部分,谢谢大家对编程字典的支持。


原文链接:https://www.cnblogs.com/kangyz/p/13859217.html