python類型轉換convert實例分析
阿新 • • 發佈:2018-02-05
base nbsp code char 創建 res 效果 ati pytho
在python的開發過程中,難免會遇到類型轉換,這裏給出常見的類型轉換demo:
類型 | 說明 |
---|---|
int(x [,base ]) | 將x轉換為一個整數 |
long(x [,base ]) | 將x轉換為一個長整數 |
float(x ) | 將x轉換到一個浮點數 |
complex(real [,imag ]) | 創建一個復數 |
str(x ) | 將對象 x 轉換為字符串 |
repr(x ) | 將對象 x 轉換為表達式字符串 |
eval(str ) | 用來計算在字符串中的有效Python表達式,並返回一個對象 |
tuple(s ) | 將序列 s 轉換為一個元組 |
list(s ) | 將序列 s 轉換為一個列表 |
chr(x ) | 將一個整數轉換為一個字符 |
unichr(x ) | 將一個整數轉換為Unicode字符 |
ord(x ) | 將一個字符轉換為它的整數值 |
hex(x ) | 將一個整數轉換為一個十六進制字符串 |
oct(x ) | 將一個整數轉換為一個八進制字符串 |
下面是我做的demo:
#類型轉換 #convert #convert to int print(‘int()默認情況下為:‘, int()) print(‘str字符型轉換為int:‘, int(‘010‘)) print(‘float浮點型轉換為int:‘, int(234.23)) #十進制數10,對應的2進制,8進制,10進制,16進制分別是:1010,12,10,0xaprint(‘int(\‘0xa\‘, 16) = ‘, int(‘0xa‘, 16)) print(‘int(\‘10\‘, 10) = ‘, int(‘10‘, 10)) print(‘int(\‘12\‘, 8) = ‘, int(‘12‘, 8)) print(‘int(\‘1010\‘, 2) = ‘, int(‘1010‘, 2)) #convert to long print(‘int浮點型轉換為int:‘, int(23)) #convert to float print(‘float()默認情況下為:‘, float()) print(‘str字符型轉換為float:‘, float(‘123.01‘)) print(‘int浮點型轉換為float:‘, float(32)) #covert to complex print(‘創建一個復數(實部+虛部):‘, complex(12, 43)) print(‘創建一個復數(實部+虛部):‘, complex(12)) #convert to str print(‘str()默認情況下為:‘, str()) print(‘float字符型轉換為str:‘, str(232.33)) print(‘int浮點型轉換為str:‘, str(32)) lists = [‘a‘, ‘b‘, ‘e‘, ‘c‘, ‘d‘, ‘a‘] print(‘列表list轉換為str:‘, ‘‘.join(lists)) #covert to list strs = ‘hongten‘ print(‘序列strs轉換為list:‘, list(strs)) #covert to tuple print(‘列表list轉換為tuple:‘, tuple(lists)) #字符和整數之間的轉換 #char coverted to int print(‘整數轉換為字符chr:‘, chr(67)) print(‘字符chr轉換為整數:‘, ord(‘C‘)) print(‘整數轉16進制數:‘, hex(12)) print(‘整數轉8進制數:‘, oct(12))
運行效果:
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>> int()默認情況下為: 0 str字符型轉換為int: 10 float浮點型轉換為int: 234 int(‘0xa‘, 16) = 10 int(‘10‘, 10) = 10 int(‘12‘, 8) = 10 int(‘1010‘, 2) = 10 int浮點型轉換為int: 23 float()默認情況下為: 0.0 str字符型轉換為float: 123.01 int浮點型轉換為float: 32.0 創建一個復數(實部+虛部): (12+43j) 創建一個復數(實部+虛部): (12+0j) str()默認情況下為: float字符型轉換為str: 232.33 int浮點型轉換為str: 32 列表list轉換為str: abecda 序列strs轉換為list: [‘h‘, ‘o‘, ‘n‘, ‘g‘, ‘t‘, ‘e‘, ‘n‘] 列表list轉換為tuple: (‘a‘, ‘b‘, ‘e‘, ‘c‘, ‘d‘, ‘a‘) 整數轉換為字符chr: C 字符chr轉換為整數: 67 整數轉16進制數: 0xc 整數轉8進制數: 0o14 >>>
python類型轉換convert實例分析