Python初學者必須掌握的25個內(nèi)置函數(shù)詳解
input()
作用:讓用戶從控制臺輸入一串字符,按下回車后結(jié)束輸入,并返回字符串
注意:很多初學者以為它可以返回數(shù)字,其實是錯的!
>>> line = input("輸入一個數(shù)字:") 輸入一個數(shù)字:1 >>> line '1' # <-- 看清楚了,這個不是數(shù)字,只是字符串 # 如果你直接進行加法…… >>> line + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str # 正確方法,先把 line 轉(zhuǎn)換成數(shù)字 >>> int(line) + 1 2
print()
作用:把參數(shù)轉(zhuǎn)換成字符串后,輸出到控制臺
>>> print("hello", "world") hello world # 很多人不知道參數(shù)之間還可以插入其他字符 >>> print("hello", "world", sep="~") hello~world # 甚至可以讓每個參數(shù)霸占一行 >>> print("hello", "world", sep="\n") hello world
set()
作用:構(gòu)造集合。一個常用的方法是,把列表傳入 set(),再轉(zhuǎn)成列表,來實現(xiàn)列表的排重。
>>> set([1, 2, 3, 3]) {1, 2, 3} # 這樣就實現(xiàn)了排重 >>> list(set([1, 2, 3, 3])) [1, 2, 3]
str()
作用:將對象轉(zhuǎn)換成字符串。常用于字符串和數(shù)字的拼接。
例如,這樣會報錯:
>>> 'My Score is: ' + 100 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str
所以要用 str 轉(zhuǎn)換一下:
>>> 'My Score is: ' + str(100) 'My Score is: 100'
chr(i)
作用:返回整數(shù) i 所對應(yīng)的字符,常用于生成字母表。
>>> chr(20013) '中' >>> chr(97) 'a' # 與 ord() 配合,生成字母表 >>> [chr(ord('a') + i) for i in range(26)] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
ord()
作用:返回字符在編碼表中對應(yīng)的十進制數(shù)值
>>> ord('中') 20013 >>> ord('a') 97 # 與 chr() 配合,生成字母表 >>> [chr(ord('a') + i) for i in range(26)] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
bool()
作用: 判斷一個對象的布爾值,返回 True 或 False
bool(1) => True bool(0) => False bool([]) => False
說明: 這個函數(shù)在實際項目中很少用,只是作為測試工具,讓初學者能了解各對象的布爾狀態(tài)。
int()
作用: 將任意進制的字符串轉(zhuǎn)化為整數(shù)。
int('2') => 2 int('1010', 2) => 10 # 2進制1010轉(zhuǎn)化為整數(shù)10
說明: 傳入第2個參數(shù),可指定參數(shù)1的進制類型。
bin()
作用: 把整數(shù)轉(zhuǎn)換成2進制的字符串
bin(2) => '0b10' bin(10) => '0b1010'
說明: 為啥字符串前面都有個 0b ?因為這是標準的寫法,以 0b 開頭表示接下來數(shù)字的是2進制。
oct()
作用: 將10進制轉(zhuǎn)換為8進制的字符串
oct(7) => '0o7' oct(8) => '0o10'
hex()
作用:將10進制轉(zhuǎn)換為16進制的字符串
>>> hex(11) '0xb' >>> hex(16) '0x10'
abs()
作用:取絕對值
>>> abs(-1) 1
divmod()
作用:同時返回除法運算中的商和余數(shù),相當于一次運算,同時得到 a//b 和 a% b 的結(jié)果。
>>> divmod(1, 2) (0, 1) >>> divmod(4, 3) (1, 1)
round()
作用:對一個浮點數(shù)進行四舍五入
>>> round(1.3333) 1 >>> round(1.3333, 2) # 2 表示保留2位小數(shù) 1.33
pow(x, y[, z])
作用:如果只填 x 和 y 參數(shù),則返回 x 的 y 次方。如果填了 z 參數(shù),則再取模,相當于 pow(x, y) % z。
>>> pow(10, 2) 100 # 相當于 >>> 10**2 100 >>> pow(10, 2, 3) 1 # 相當于 >>> 10**2 % 3 1
sum(iterable)
作用:對數(shù)組 iterable 的所有元素進行求和。
>>> sum([1, 2, 3]) 6
min(x, y, z, …)
作用:返回所有參數(shù)中的最小數(shù)
>>> min(1, 2, 3) 1 # 傳入數(shù)組也可以 >>> min([1, 2, 3]) 1
max(x, y, z, …)
作用:類似 min(),返回所有參數(shù)中的最大數(shù)
list()
作用:傳入?yún)?shù)為空時,創(chuàng)建列表;傳入?yún)?shù)不為空時,將參數(shù)轉(zhuǎn)換成列表
>>> list() [] # 不為空時 >>> list('hello world') ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] # 傳入字典試試 >>> list({'a': 1, 'b': 2}) ['a', 'b']
tuple()
作用:跟 list 幾乎一模一樣,只不過 list 返回的是數(shù)組,tuple 返回的是元組。
dict()
作用:構(gòu)造字典
# 方法1: >>> dict(a=1, b=2) {'a': 1, 'b': 2} # 方法2: >>> dict(zip(['a', 'b'], [1, 2])) {'a': 1, 'b': 2} # 方法3: >>> dict([('a', 1), ('b', 2)]) {'a': 1, 'b': 2}
len()
作用:返回對象長度,或元素個數(shù)
>>> len([1, 2]) 2 >>> len({'a': 1, 'b': 2}) 2 >>> len('hello') 5
reversed()
作用:反轉(zhuǎn)列表。
注意:返回的不是列表,是個迭代器。
>>> reversed([1, 2, 3]) <list_reverseiterator object at 0x1016190a0> # 需要轉(zhuǎn)換成 list >>> list(reversed([1, 2, 3])) [3, 2, 1] # 字符串也一樣 >>> reversed('abc') <reversed object at 0x1015ffd90> >>> list(reversed('abc')) ['c', 'b', 'a']
enumerate()
作用:用于遍歷對象,正常的遍歷,比如 for el in array ,只能拿到元素,不能拿到下標,用 enumerate() 就可以。
>>> for i, el in enumerate('abc'): ... print(i, el) ... 0 a 1 b 2 c
這個下標怎么用呢?比如可以用來反過來修改數(shù)組內(nèi)的元素:
>>> alphabet = ['a', 'b', 'c'] >>> for i, el in enumerate(alphabet): ... alphabet[i] = el.upper() ... >>> alphabet ['A', 'B', 'C']
filter(func, iterable)
作用:過濾并返回符合條件的元素
注意:返回的是一個迭代器。
>>> alphabet = ['a', 'b', 'c', 'E', 'F', 'G'] >>> filter(lambda e: e.isupper(), alphabet) <filter object at 0x1016190a0> >>> list(filter(lambda e: e.isupper(), alphabet)) ['E', 'F', 'G']
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。