Python数据类型的转换
变量的数据类型非常重要,通常情况下只有相同类型的变量才能进行运算。Python 具有简单的数据类型自动转换功能: 如果是整数与浮点运算,系统会先将整数转换为浮点数再运算, 运算结果为浮点型,例如:
>>> num1 = 5 + 7.8
>>> num1
12.8
若是数值与布尔值运算, 系统会先将布尔值转换为数值再运算,即把True转换为1, Flase转换为0 。例如:
>>> num2 = 5 + True
>>> num2
6
如果系统无法自动进行数据类型转换,就要用数据类型转换命令进行强制转换。Python 的强制数据类型转换命令有:
1.int(): 强制转换为整型。
2.float(): 强制转换为浮点型。
3.str(): 强制转换为字符串型。
整数与字符串相加会产生错误, 例如:
>>> num3 = 23 + "67"
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
num3 = 23 + "67"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
把字符串转换为整数再进行运算即可正常执行:
>>> num3 = 23 + int("67")
>>> num3
90
用print 打印字符串时,若把字符串和数值相加会产生错误:
>>> score = 60
>>> print("小明的成绩为 "+ score)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
print("小明的成绩为 "+ score)
TypeError: can only concatenate str (not "int") to str
把数值转换为字符串再进行相加即可正常执行:
>>> score = 60
>>> print("小明的成绩为 "+ str(score))
小明的成绩为 60