Python基础知识(类型转换_str()函数与int()函数、类型转换_float()函数、Python中的注释、)

本文介绍了Python中数据类型转换的重要性和方法,包括使用_str()、int()和_float()函数进行转换,并详细讲解了如何进行注释,以提高代码可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为什么需要数据类型转换?

将不同数据类型的数据拼接在一起

name='张三'
age=20
print(type(name),type(age))#说明name与age的数据类型不相同
print('我叫'+name+'今年,'+str(age)+'岁')#将int类型通过str()函数转成了str类型


#结果
<class 'str'> <class 'int'>
我叫张三今年,20岁
name='张三'
age=20
print(type(name),type(age))#说明name与age的数据类型不相同
print('我叫'+name+'今年,'+age+'岁')#当将str与int类型进行连接时,报错,解决方案,类型转换


#结果
    print('我叫'+name+'今年,'+age+'岁')#当将str与int类型进行连接时,报错,解决方案,类型转换
TypeError: can only concatenate str (not "int") to str

16.类型转换_float()函数

数据类型转换

为什么需要数据类型转换?

讲不同数据类型的数据拼接在一起

s1='13.14'
s2='52'
l1=True
s3='hello'
i=100
print(type(s1),type(s2),type(l1),type(s3),type(i))
print(float(s1),type(float(s1)))
print(float(s2),type(float(s2)))
print(float(l1),type(float(l1)))
#print(float(s3),type(float(s3))) #字符串中的数据如果是非数字串,则不允许转换
print(float(i),type(float(i)))

#结果
<class 'str'> <class 'str'> <class 'bool'> <class 'st
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值