1. 程式人生 > 其它 >python常見的資料型別轉換str() int() float()使用

python常見的資料型別轉換str() int() float()使用

為什麼需要資料型別轉換呢?
將不同的資料的資料拼接在一起

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’>