
3.7 类型判断与类型间转换
通过上面的学习,大概了解了Python的基本数据类型。在Python中,还提供了相关内置函数,对不同类型进行相互转换。下面详细介绍各种类型之间的转换方式。
3.7.1 数据类型的判断
在对数据转换之前,需要学会判断数据的类型。Python提供了内置函数type(),可以对任何数据的类型进行判断。其语法格式如下:

其中,x表示数据或对象。
【实例3-17】对不同类型的数据进行判断,并查看判断结果。
(1)判断整数数据的类型,代码如下:

输出结果表示,整数类型判断结果为“int”。
(2)判断浮点数数据的类型,代码如下:

输出结果表示,浮点数数据类型判断结果为“float”。
(3)判断字符串数据的类型,代码如下:

输出结果表示,字符串数据类型判断结果为“str”。
3.7.2 整数类型转换为二进制字符串
Python提供了内置函数bin(),它可以将整数类型转换为二进制整数的字符串形式。其语法格式如下:

其中,x为整数类型。
助记:bin()中的bin取自二进制对应的英文单词binary中的前3个字母。
【实例3-18】下面依次将几种不同进制类型的整数转换为二进制字符串。

3.7.3 整数类型转换为八进制字符串
Python提供了内置函数oct(),它可以将整数类型转换为八进制整数的字符串形式。其语法格式如下:

其中,x为整数类型。
助记:oct()中的oct取自单词octal中的前3个字母。
【实例3-19】下面依次将几种不同进制类型的整数转换为八进制字符串。

3.7.4 整数类型转换为十六进制字符串
Python提供了内置函数hex(),它可以将整数类型转换为十六进制整数的字符串形式。其语法格式如下:

其中,x为整数类型。
助记:hex()中的hex取自单词hexadecimal中的前3个字母。
【实例3-20】下面依次将几种不同进制类型的整数转换为十六进制字符串。

3.7.5 其他类型转换为整数类型
为了方便转换,Python提供了内置函数int(),它可以将数字类型、字符串类型转换为整数类型。其语法格式如下:

其中,x表示数字或字符串,base表示进制数,默认为十进制整数。
助记:int()中的int取自单词integer中的前3个字母。
下面介绍该函数的使用。
1. 不使用任何参数的情况
不使用任何参数时,得到的结果为0。
【实例3-21】将空类型值转换为整数类型,代码及执行结果如下:

2. 参数x为整数、浮点数类型的情况
该情况不需要使用base参数。其作用是对参数x取整。
【实例3-22】将整数、浮点数转换为整数类型,代码及执行结果如下:

3. 参数x为进制整数的情况
该情况也不需要使用base参数。其作用是将进制整数转换为十进制整数。
【实例3-23】将不同进制的整数转换为十进制整数,代码及执行结果如下:

4. 参数x为字符串的情况
该情况下,参数base可有可无,下面介绍这两种情况。
(1)无参数base
所谓的无参数base,其实不是没有,而是使用了默认的参数值base=10。在这种情况下,参数x必须是十进制整数的字符串,否则会报错。
【实例3-24】对无参数base的字符串转换为整数类型,代码及执行结果如下:

(2)有参数base
有参数base时,参数x的类型要与参数base表示的进制保持一致,否则会报错。
【实例3-25】对既有参数x,又有参数base的不同情况的整数转换,代码及执行结果如下:

3.7.6 其他类型转换为字符串类型
Python提供了内置函数str(),它可以将其他类型转换为字符串类型。其语法格式如下:

其中,x可以为字符串、整数类型等。下面介绍该函数的使用。
助记:str()中的str取自单词string中的前3个字母。
1. x为字符串情况
该情况不进行转换,直接输入x本身。
【实例3-26】将不同类型的字符串转换为字符串类型,代码及执行结果如下:

2. x为整数类型情况
该情况下会将整数类型转换为十进制整数字符串类型。
【实例3-27】将不同整数类型转换为字符串类型,代码及执行结果如下:

3.7.7 其他类型转换为浮点数类型
Python提供了内置函数float(),它可以将数字和字符串转换为字符串类型。其语法格式如下:

其中,x可以为浮点数、整数、字符串。下面介绍该函数的使用。
1. x为浮点数情况
该情况不进行转换,直接输入x本身。
【实例3-28】将浮点数类型转换为浮点数类型,代码及执行结果如下:

2. x为整数情况
该情况下会将整数类型转换为浮点数类型。
【实例3-29】将不同类型的整数转换为浮点数类型,代码及执行结果如下:

3. x为字符串情况
该情况下会将字符串类型转换为浮点数类型。
【实例3-30】将不同类型的字符串转换为浮点数,代码及执行结果如下:
