Python--Demo4--类型转换函数

1、str()函数:将参数值转换成字符串类型的值,并返回。

情景:

在使用打印函数的时候如果用到字符串链接数字的情况,我们需要使用str()函数将数值转换成字符串,然后使用+操作符连接。

示例:

>>> number=12 >>> print('我有'+number+'个苹果') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str

说明:

上面是一个错误示例

报错原因最后面一行说了:只能将str和str连接

所以:我们必须得通过一种手段将int转换成str来能输出。

所以:python中连接字符串和数值,我们只能先将数值转换成字符串,再进行连接

>>> print('我有'+str(number)+'个苹果')
我有12个苹果

2、int()函数:将数字形式的字符串值转换成整型,并返回。

情景:

当我们使用Input()函数的时候,我们知道input()从控制台中接收的输入信息后返回的都是字符串值,我们如果想对用户输入的数字进行算数运算就得使用int()进行转换。

示例:

>>> age=input('输入你的年龄:')
输入你的年龄:12
>>> type(age)
<class 'str'>
>>> new_age=age+10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> new_age=int(age)+10
>>> new_age
22

说明:

  • 第一行使用变量age接收input()的返回值;
  • 接着我们使用了python内置的type()函数进行类型探测。返回的类型信息是:str类型
  • 我们使用str直接进行加法运算,报错了!报错信息是:不能将字符串和数字进行连接操作?竟然把加号看作了字符串连接运算符
  • 最后使用int()函数将字符串进行了转换,成功。

猜你喜欢

转载自www.cnblogs.com/bigbosscyb/p/12317014.html