数据类型转换失败:str, int, float互转
在Python中,str
, int
, 和 float
类型之间可以进行转换。以下是详细的解释:
str
转换为int
或float
:直接使用整数除法(//)或浮点数除法(/)进行转换:
s = "123"
i = int(s) # str转int
f = float(s) # str转float
print(i) # 输出:123
print(f) # 输出:123.0
使用
str.isdigit()
或str.isnumeric()
方法判断字符串是否为数字,然后进行转换:s = "123"
if s.replace('.', '', 1).isdigit(): # 去掉小数点
i = int(s)
f = float(s)
print(i) # 输出:123
print(f) # 输出:123.0
int
或float
转换为str
:直接使用格式化字符串(f-string)或字符串连接方法(如
+
,*
)进行转换:i = 42
f = 3.14
s_int = str(i)
s_float = str(f)
print(s_int) # 输出:42
print(s_float) # 输出:3.14
注意:在转换过程中,如果数据类型不匹配或者超出Python支持的范围,可能会导致错误。
还没有评论,来说两句吧...