Python int() 函數
描述
int() 函數用於將一個字符串或數字轉換為整型。
語法
以下是 int() 方法的語法:
class int(x, base=10)
參數
- x -- 字符串或數字。
- base -- 進制數,默認十進制。
返回值
返回整型數據。
實例
以下展示了使用 int() 方法的實例:
>>> int(3)
3
>>> int(3.6)
3
>>> int('12',16)
18
>>> int('12',16)#如果帶參數base的話,12要以字符串的形式輸入,12為6進制
18
>>> int('0xa',16)
10
>>> int('10',8)
8
>>> int()#不傳入參數時,得0
0
>>> int(0)
0

Python 內置函數
deepblue
nak***139@163.com
怒寫一波:
int(x,base)x 有兩種:str / int
1、若 x 為純數字,則不能有 base 參數,否則報錯;其作用為對入參 x 取整
>>> int(-11.233) -11 >>> int(2.5,10) Traceback (most recent call last): File "<pyshell#51>", line 1, in <module> int(2.5,10) TypeError: int() can't convert non-string with explicit base >>> int(2.5) 22、若 x 為 str,則 base 可略可有。
base 存在時,視 x 為 base 類型數字,並將其轉換為 10 進制數字。
若 x 不符合 base 規則,則報錯。如:
>>> int("9",2)#報錯,因為2進制無9 Traceback (most recent call last): File "<pyshell#66>", line 1, in <module> int("9",2)#報錯,因為2進制無9 ValueError: invalid literal for int() with base 2: '9' >>> int('9') 9 >>> >>> int('3.14',8) Traceback (most recent call last): File "<pyshell#69>", line 1, in <module> int('3.14',8) ValueError: invalid literal for int() with base 8: '3.14' >>> int("1.2")#均報錯,str須為整數 Traceback (most recent call last): File "<pyshell#70>", line 1, in <module> int("1.2")#均報錯,str須為整數 ValueError: invalid literal for int() with base 10: '1.2' >>> >>> int("1001",2) 9 >>> #"1001"才是2進制,並轉化為十進制數字9 >>> int("0xa",16) 10 >>> #≥16進制才會允許入參a,b,c,... >>> int("b",8) Traceback (most recent call last): File "<pyshell#76>", line 1, in <module> int("b",8) ValueError: invalid literal for int() with base 8: 'b' >>> >>> int("123",8) 83 >>> #視123為8進制數字,對應的10進制為83 >>>