為什么需要數據類型轉換呢?
將不同的數據的數據拼接在一起
str()是將其他數據類型轉換成字符串,也可以引號轉換,str(123)等價於’123’
int()是將其他數據類型轉換成整數:
注意:
1、文字類和小數類字符串,無法轉換成整數
2、浮點數轉換成整數,小數部分舍掉,只要整數部分
例如:
int(‘123’)=123
int(‘9.8’)=9
float()是將其他數據類型轉換成浮點數
注意:
1、文字類無法轉換成浮點型;
2、整數轉換成浮點數,末尾.0
例如:
float(‘9.9’)=9.9
float(9)=9.0
name='張三' age=20 print(type(name),type(age)) #說明name和age數據類型不相同 #print('我叫'+name+'今年'+age+'歲') #當將數據類型不相同進行拼接時,就會報錯,解決方案,類型轉換 print('我叫'+name+','+'今年'+str(age)+'歲')#將int的類型轉換成str類型,進行拼接就不會報錯了 print('---------str()將其他類型轉換成str類型--------------------') a=19 b=198.8 c=False print(type(a),type(b),type(c)) print(str(a),str(b),str(c),type(str(a)),type(str(b)),type(str(c))) print('-------------int()將其他的類型轉換成int類型--------------') s1='128' f1=98.7 s2='76.77' f3=True s3='hello' print(type(s1),type(f1),type(s2),type(f3),type(s3)) print(int(s1),type(int(s1))) #將str轉成int類型,字符串為數字串 print(int(f1),type(int(f1))) #float轉成int類型,截取整數部分,舍掉小數部分 #print(int(s2),type(int(s2))) #將str轉成int類型,報錯,因為字符串為小數串 print(int(f3),type(int(f3))) # #print(int(s3),type(int(s3))) #將str轉成int類型時,字符串必須是不帶小數的數字串 print('---------------float(),將其他類型轉成float類型----------------') s1='128.98' s2='76' f3=True s3='hello' i=98 print(type(s1),type(s2),type(f3),type(s3),type(i)) print(float(s1),type(float(s1))) print(float(s2),type(float(s2))) print(float(f3),type(float(f3))) #print(float(s3),type(float(s3))) #z字符串中的數據如果是非字符串,則不允許轉換 print(float(i),type(float(i)))
運行結果:
<class ‘str’> <class ‘int’>
我叫張三,今年20歲
---------str()將其他類型轉換成str類型--------------------
<class ‘int’> <class ‘float’> <class ‘bool’>
19 198.8 False <class ‘str’> <class ‘str’> <class ‘str’>
-------------int()將其他的類型轉換成int類型--------------
<class ‘str’> <class ‘float’> <class ‘str’> <class ‘bool’> <class ‘str’>
128 <class ‘int’>
98 <class ‘int’>
1 <class ‘int’>
---------------float(),將其他類型轉成float類型----------------
<class ‘str’> <class ‘str’> <class ‘bool’> <class ‘str’> <class ‘int’>
128.98 <class ‘float’>
76.0 <class ‘float’>
1.0 <class ‘float’>
98.0 <class ‘float’>