Python中100個(gè)常用函數(shù)用法全面解析
Python 100個(gè)常用函數(shù)全面解析
1. 類型轉(zhuǎn)換函數(shù)
1.1 int()
將字符串或數(shù)字轉(zhuǎn)換為整數(shù)。
# 基本用法
int('123') # 123
int(3.14) # 3
# 指定進(jìn)制轉(zhuǎn)換
int('1010', 2) # 10 (二進(jìn)制轉(zhuǎn)十進(jìn)制)
int('FF', 16) # 255 (十六進(jìn)制轉(zhuǎn)十進(jìn)制)
# 臨界值處理
int('') # ValueError: invalid literal for int() with base 10: ''
int(None) # TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
int('3.14') # ValueError: invalid literal for int() with base 10: '3.14'
int(float('inf')) # OverflowError: cannot convert float infinity to integer
1.2 float()
將數(shù)據(jù)轉(zhuǎn)換為浮點(diǎn)數(shù)。
# 基本用法
float('3.14') # 3.14
float(3) # 3.0
# 特殊值轉(zhuǎn)換
float('inf') # inf
float('-inf') # -inf
float('nan') # nan
# 臨界值處理
float('') # ValueError: could not convert string to float: ''
float(None) # TypeError: float() argument must be a string or a number, not 'NoneType'
float('3.14a') # ValueError: could not convert string to float: '3.14a'
1.3 str()
將對(duì)象轉(zhuǎn)換為字符串。
# 基本用法
str(123) # '123'
str(3.14) # '3.14'
str(True) # 'True'
# 特殊對(duì)象轉(zhuǎn)換
str(None) # 'None'
str([1,2,3]) # '[1, 2, 3]'
# 臨界值處理
str(float('inf')) # 'inf'
str(float('nan')) # 'nan'
str(object()) # '<object object at 0x...>'
1.4 bool()
將值轉(zhuǎn)換為布爾類型。
# 基本用法
bool(1) # True
bool(0) # False
bool('') # False
bool('abc') # True
# 特殊值轉(zhuǎn)換
bool(None) # False
bool([]) # False
bool([0]) # True
# 臨界值處理
bool(float('inf')) # True
bool(float('nan')) # True
1.5 list()
創(chuàng)建列表或?qū)⒖傻鷮?duì)象轉(zhuǎn)換為列表。
# 基本用法
list('abc') # ['a', 'b', 'c']
list((1,2,3)) # [1, 2, 3]
# 空列表創(chuàng)建
list() # []
# 臨界值處理
list(None) # TypeError: 'NoneType' object is not iterable
list(123) # TypeError: 'int' object is not iterable
list({'a':1}) # ['a'] (字典默認(rèn)迭代鍵)
1.6 tuple()
創(chuàng)建元組或?qū)⒖傻鷮?duì)象轉(zhuǎn)為元組。
# 基本用法
tuple([1,2,3]) # (1, 2, 3)
tuple('abc') # ('a', 'b', 'c')
# 空元組創(chuàng)建
tuple() # ()
# 臨界值處理
tuple(None) # TypeError: 'NoneType' object is not iterable
tuple(123) # TypeError: 'int' object is not iterable
1.7 set()
創(chuàng)建集合或去除可迭代對(duì)象中的重復(fù)元素。
# 基本用法
set([1,2,2,3]) # {1, 2, 3}
set('aabbcc') # {'a', 'b', 'c'}
# 空集合創(chuàng)建
set() # set()
# 臨界值處理
set(None) # TypeError: 'NoneType' object is not iterable
set(123) # TypeError: 'int' object is not iterable
set([[]]) # TypeError: unhashable type: 'list'
1.8 dict()
創(chuàng)建字典。
# 基本用法
dict(a=1, b=2) # {'a': 1, 'b': 2}
dict([('a',1),('b',2)]) # {'a': 1, 'b': 2}
# 空字典創(chuàng)建
dict() # {}
# 臨界值處理
dict(None) # TypeError: cannot convert dictionary update sequence element #0 to a sequence
dict(123) # TypeError: cannot convert dictionary update sequence element #0 to a sequence
dict([('a',1), None]) # TypeError: cannot convert dictionary update sequence element #1 to a sequence
2. 輸入輸出函數(shù)
2.9 input()
從控制臺(tái)讀取用戶輸入的字符串。
# 基本用法
# name = input("請(qǐng)輸入你的名字: ") # 用戶輸入會(huì)作為字符串返回
# 臨界值處理
# 輸入Ctrl+D (Unix) 或 Ctrl+Z (Windows) 會(huì)引發(fā) EOFError
2.10 print()
將指定的對(duì)象輸出到控制臺(tái)。
# 基本用法
print('Hello', 'World') # Hello World
print(1, 2, 3, sep='-') # 1-2-3
# 參數(shù)說明
# sep: 分隔符,默認(rèn)為空格
# end: 結(jié)束字符,默認(rèn)為換行符
# file: 輸出文件對(duì)象,默認(rèn)為sys.stdout
# flush: 是否立即刷新緩沖區(qū),默認(rèn)為False
# 臨界值處理
print(None) # None
print(float('inf')) # inf
print(float('nan')) # nan
3. 數(shù)學(xué)運(yùn)算函數(shù)
3.11 abs()
返回一個(gè)數(shù)的絕對(duì)值。
# 基本用法
abs(-5) # 5
abs(3.14) # 3.14
# 復(fù)數(shù)絕對(duì)值
abs(3+4j) # 5.0 (返回模)
# 臨界值處理
abs(float('inf')) # inf
abs(float('-inf')) # inf
abs(float('nan')) # nan
3.12 max()
返回可迭代對(duì)象中的最大值。
# 基本用法
max([1, 2, 3]) # 3
max('a', 'b', 'c') # 'c'
# 指定key函數(shù)
max(['apple', 'banana', 'cherry'], key=len) # 'banana'
# 臨界值處理
max([]) # ValueError: max() arg is an empty sequence
max([float('nan'), 1, 2]) # nan (但比較nan的行為可能不一致)
max([None, 1, 2]) # TypeError: '>' not supported between instances of 'int' and 'NoneType'
3.13 min()
返回可迭代對(duì)象中的最小值。
# 基本用法
min([1, 2, 3]) # 1
min('a', 'b', 'c') # 'a'
# 指定key函數(shù)
min(['apple', 'banana', 'cherry'], key=len) # 'apple'
# 臨界值處理
min([]) # ValueError: min() arg is an empty sequence
min([float('nan'), 1, 2]) # nan (但比較nan的行為可能不一致)
min([None, 1, 2]) # TypeError: '<' not supported between instances of 'int' and 'NoneType'
3.14 sum()
對(duì)可迭代對(duì)象中的元素求和。
# 基本用法
sum([1, 2, 3]) # 6
sum([1.5, 2.5, 3]) # 7.0
# 指定起始值
sum([1, 2, 3], 10) # 16
# 臨界值處理
sum([]) # 0
sum(['a', 'b']) # TypeError: unsupported operand type(s) for +: 'int' and 'str'
sum([float('inf'), 1]) # inf
sum([float('nan'), 1]) # nan
3.15 round()
對(duì)浮點(diǎn)數(shù)進(jìn)行四舍五入。
# 基本用法
round(3.14159) # 3
round(3.14159, 2) # 3.14
# 銀行家舍入法(四舍六入五成雙)
round(2.5) # 2
round(3.5) # 4
# 臨界值處理
round(float('inf')) # inf
round(float('nan')) # nan
round(123.456, -2) # 100.0 (負(fù)的ndigits參數(shù))
round(123.456, 300) # 123.456 (過大ndigits參數(shù))
4. 字符串操作函數(shù)
4.16 len()
返回對(duì)象的長(zhǎng)度或元素個(gè)數(shù)。
# 基本用法
len('abc') # 3
len([1,2,3]) # 3
len({'a':1}) # 1
# 臨界值處理
len('') # 0
len(None) # TypeError: object of type 'NoneType' has no len()
len(123) # TypeError: object of type 'int' has no len()
4.17 str.split()
以指定字符為分隔符分割字符串。
# 基本用法
'apple,banana,cherry'.split(',') # ['apple', 'banana', 'cherry']
# 指定最大分割次數(shù)
'apple,banana,cherry'.split(',', 1) # ['apple', 'banana,cherry']
# 臨界值處理
''.split(',') # ['']
' '.split() # [] (默認(rèn)分割空白字符)
None.split() # AttributeError: 'NoneType' object has no attribute 'split'
4.18 str.join()
用指定字符串連接可迭代對(duì)象中的字符串元素。
# 基本用法
','.join(['a', 'b', 'c']) # 'a,b,c'
'-'.join('abc') # 'a-b-c'
# 臨界值處理
''.join([]) # ''
','.join([1, 2, 3]) # TypeError: sequence item 0: expected str instance, int found
','.join(None) # TypeError: can only join an iterable
4.19 str.find()
在字符串中查找子串,返回首次出現(xiàn)的索引。
# 基本用法
'hello world'.find('world') # 6
'hello world'.find('o') # 4
# 臨界值處理
'hello'.find('x') # -1 (未找到)
''.find('') # 0
'hello'.find('') # 0
'hello'.find(None) # TypeError: must be str, not NoneType
4.20 str.rfind()
從右側(cè)開始查找子串。
# 基本用法
'hello world'.rfind('o') # 7
# 臨界值處理
'hello'.rfind('x') # -1
''.rfind('') # 0
'hello'.rfind('', 10) # 5 (超過字符串長(zhǎng)度)
4.21 str.replace()
替換字符串中的指定子串。
# 基本用法
'hello world'.replace('world', 'Python') # 'hello Python'
# 指定替換次數(shù)
'ababab'.replace('a', 'c', 2) # 'cbcbab'
# 臨界值處理
'hello'.replace('', '-') # '-h-e-l-l-o-'
'hello'.replace('x', 'y') # 'hello' (無匹配)
'hello'.replace(None, 'y') # TypeError: replace() argument 1 must be str, not NoneType
4.22 str.strip()
去除字符串兩端的空白字符。
# 基本用法
' hello '.strip() # 'hello'
'\thello\n'.strip() # 'hello'
# 指定去除字符
'xxhelloxx'.strip('x') # 'hello'
# 臨界值處理
''.strip() # ''
' '.strip() # ''
None.strip() # AttributeError
4.23 str.lstrip()
去除字符串左側(cè)的空白字符。
# 基本用法 ' hello '.lstrip() # 'hello ' # 臨界值處理 ''.lstrip() # '' None.lstrip() # AttributeError
4.24 str.rstrip()
去除字符串右側(cè)的空白字符。
# 基本用法 ' hello '.rstrip() # ' hello' # 臨界值處理 ''.rstrip() # '' None.rstrip() # AttributeError
4.25 str.upper()
將字符串轉(zhuǎn)換為大寫。
# 基本用法 'Hello'.upper() # 'HELLO' # 臨界值處理 ''.upper() # '' '123'.upper() # '123' None.upper() # AttributeError
4.26 str.lower()
將字符串轉(zhuǎn)換為小寫。
# 基本用法 'Hello'.lower() # 'hello' # 臨界值處理 ''.lower() # '' '123'.lower() # '123' None.lower() # AttributeError
4.27 str.title()
將每個(gè)單詞的首字母大寫。
# 基本用法 'hello world'.title() # 'Hello World' # 臨界值處理 ''.title() # '' "they're bill's".title() # "They'Re Bill'S" (注意撇號(hào)后的字母) None.title() # AttributeError
5. 列表操作函數(shù)
5.28 list.append()
在列表末尾添加元素。
# 基本用法 lst = [1, 2] lst.append(3) # lst變?yōu)閇1, 2, 3] # 臨界值處理 lst.append(None) # lst變?yōu)閇1, 2, 3, None] lst.append(lst) # 可以添加自身(創(chuàng)建循環(huán)引用)
5.29 list.extend()
用可迭代對(duì)象擴(kuò)展列表。
# 基本用法
lst = [1, 2]
lst.extend([3, 4]) # lst變?yōu)閇1, 2, 3, 4]
# 臨界值處理
lst.extend('abc') # lst變?yōu)閇1, 2, 3, 4, 'a', 'b', 'c']
lst.extend(None) # TypeError: 'NoneType' object is not iterable
5.30 list.insert()
在指定位置插入元素。
# 基本用法 lst = [1, 3] lst.insert(1, 2) # lst變?yōu)閇1, 2, 3] # 臨界值處理 lst.insert(-10, 0) # 插入到最前面 lst.insert(100, 4) # 插入到最后面 lst.insert(1, None) # 可以插入None
5.31 list.remove()
移除列表中指定值的第一個(gè)匹配項(xiàng)。
# 基本用法 lst = [1, 2, 3, 2] lst.remove(2) # lst變?yōu)閇1, 3, 2] # 臨界值處理 lst.remove(4) # ValueError: list.remove(x): x not in list lst.remove(None) # 如果列表中有None可以移除
5.32 list.pop()
移除并返回指定位置的元素。
# 基本用法 lst = [1, 2, 3] lst.pop() # 返回3, lst變?yōu)閇1, 2] lst.pop(0) # 返回1, lst變?yōu)閇2] # 臨界值處理 lst.pop(100) # IndexError: pop index out of range [].pop() # IndexError: pop from empty list
5.33 list.index()
返回指定元素的索引。
# 基本用法 lst = [1, 2, 3, 2] lst.index(2) # 1 # 指定搜索范圍 lst.index(2, 2) # 3 # 臨界值處理 lst.index(4) # ValueError: 4 is not in list [].index(1) # ValueError: 1 is not in list
5.34 list.count()
返回指定元素的出現(xiàn)次數(shù)。
# 基本用法 lst = [1, 2, 3, 2] lst.count(2) # 2 # 臨界值處理 lst.count(4) # 0 [].count(1) # 0 lst.count(None) # 0 (除非列表中有None)
5.35 list.sort()
對(duì)列表進(jìn)行原地排序。
# 基本用法 lst = [3, 1, 2] lst.sort() # lst變?yōu)閇1, 2, 3] # 指定key和reverse lst.sort(reverse=True) # 降序排序 lst.sort(key=lambda x: -x) # 按負(fù)值排序 # 臨界值處理 lst = [1, 'a', 2] # TypeError: '<' not supported between instances of 'str' and 'int' [].sort() # 無操作
5.36 list.reverse()
反轉(zhuǎn)列表中的元素順序。
# 基本用法 lst = [1, 2, 3] lst.reverse() # lst變?yōu)閇3, 2, 1] # 臨界值處理 [].reverse() # 無操作
6. 字典操作函數(shù)
6.37 dict.keys()
返回字典的鍵視圖。
# 基本用法
d = {'a':1, 'b':2}
d.keys() # dict_keys(['a', 'b'])
# 臨界值處理
{}.keys() # dict_keys([])
6.38 dict.values()
返回字典的值視圖。
# 基本用法
d = {'a':1, 'b':2}
d.values() # dict_values([1, 2])
# 臨界值處理
{}.values() # dict_values([])
6.39 dict.items()
返回字典的鍵值對(duì)視圖。
# 基本用法
d = {'a':1, 'b':2}
d.items() # dict_items([('a', 1), ('b', 2)])
# 臨界值處理
{}.items() # dict_items([])
6.40 dict.get()
獲取指定鍵的值,不存在則返回默認(rèn)值。
# 基本用法
d = {'a':1, 'b':2}
d.get('a') # 1
d.get('c', 0) # 0
# 臨界值處理
d.get('c') # None (不指定默認(rèn)值時(shí))
6.41 dict.pop()
移除并返回指定鍵的值。
# 基本用法
d = {'a':1, 'b':2}
d.pop('a') # 1, d變?yōu)閧'b':2}
# 指定默認(rèn)值
d.pop('c', 0) # 0
# 臨界值處理
d.pop('c') # KeyError: 'c'
{}.pop('a') # KeyError: 'a'
6.42 dict.popitem()
隨機(jī)移除并返回一個(gè)鍵值對(duì)。
# 基本用法
d = {'a':1, 'b':2}
d.popitem() # 可能是 ('a', 1) 或 ('b', 2)
# 臨界值處理
{}.popitem() # KeyError: 'popitem(): dictionary is empty'
6.43 dict.update()
用另一個(gè)字典更新當(dāng)前字典。
# 基本用法
d = {'a':1}
d.update({'b':2}) # d變?yōu)閧'a':1, 'b':2}
# 多種更新方式
d.update(b=3, c=4) # d變?yōu)閧'a':1, 'b':3, 'c':4}
# 臨界值處理
d.update(None) # TypeError: 'NoneType' object is not iterable
d.update(1) # TypeError: cannot convert dictionary update sequence element #0 to a sequence
7. 文件操作函數(shù)
7.44 open()
打開文件并返回文件對(duì)象。
# 基本用法
# f = open('file.txt', 'r') # 以只讀方式打開文件
# 常用模式
# 'r' - 讀取 (默認(rèn))
# 'w' - 寫入 (會(huì)截?cái)辔募?
# 'a' - 追加
# 'b' - 二進(jìn)制模式
# '+' - 讀寫模式
# 臨界值處理
# open('nonexistent.txt', 'r') # FileNotFoundError
# open('/invalid/path', 'w') # PermissionError 或其他OSError
7.45 file.read()
讀取文件內(nèi)容。
# 基本用法
# with open('file.txt') as f:
# content = f.read() # 讀取全部?jī)?nèi)容
# 指定讀取大小
# f.read(100) # 讀取100個(gè)字符
# 臨界值處理
# f.read() 在文件關(guān)閉后調(diào)用會(huì)引發(fā) ValueError
7.46 file.readline()
讀取文件的一行。
# 基本用法
# with open('file.txt') as f:
# line = f.readline() # 讀取一行
# 臨界值處理
# 文件末尾返回空字符串 ''
7.47 file.readlines()
讀取所有行并返回列表。
# 基本用法
# with open('file.txt') as f:
# lines = f.readlines() # 返回行列表
# 臨界值處理
# 空文件返回空列表 []
7.48 file.write()
將字符串寫入文件。
# 基本用法
# with open('file.txt', 'w') as f:
# f.write('hello\n') # 寫入字符串
# 臨界值處理
# 只能寫入字符串,寫入其他類型會(huì)引發(fā) TypeError
# f.write(123) # TypeError
7.49 file.close()
關(guān)閉文件。
# 基本用法
# f = open('file.txt')
# f.close()
# 臨界值處理
# 多次調(diào)用close()不會(huì)報(bào)錯(cuò)
# 使用with語句更安全,會(huì)自動(dòng)關(guān)閉文件
8. 迭代器與生成器函數(shù)
8.50 range()
生成整數(shù)序列。
# 基本用法 list(range(5)) # [0, 1, 2, 3, 4] list(range(1, 5)) # [1, 2, 3, 4] list(range(1, 10, 2)) # [1, 3, 5, 7, 9] # 臨界值處理 list(range(0)) # [] list(range(1, 1)) # [] list(range(1, 5, -1)) # []
8.51 enumerate()
返回枚舉對(duì)象(索引和元素)。
# 基本用法 list(enumerate(['a', 'b', 'c'])) # [(0, 'a'), (1, 'b'), (2, 'c')] # 指定起始索引 list(enumerate(['a', 'b'], 1)) # [(1, 'a'), (2, 'b')] # 臨界值處理 list(enumerate([])) # [] list(enumerate(None)) # TypeError: 'NoneType' object is not iterable
8.52 zip()
將多個(gè)可迭代對(duì)象打包成元組。
# 基本用法 list(zip([1, 2], ['a', 'b'])) # [(1, 'a'), (2, 'b')] # 不同長(zhǎng)度處理 list(zip([1, 2, 3], ['a', 'b'])) # [(1, 'a'), (2, 'b')] # 臨界值處理 list(zip()) # [] list(zip([], [])) # [] list(zip([1], None)) # TypeError: zip argument #2 must support iteration
9. 函數(shù)式編程函數(shù)
9.53 map()
將函數(shù)應(yīng)用于可迭代對(duì)象的每個(gè)元素。
# 基本用法 list(map(str, [1, 2, 3])) # ['1', '2', '3'] list(map(lambda x: x*2, [1, 2, 3])) # [2, 4, 6] # 多個(gè)可迭代對(duì)象 list(map(lambda x,y: x+y, [1,2], [3,4])) # [4, 6] # 臨界值處理 list(map(str, [])) # [] list(map(None, [1,2])) # TypeError: 'NoneType' object is not callable
9.54 filter()
根據(jù)函數(shù)條件過濾元素。
# 基本用法 list(filter(lambda x: x>0, [-1, 0, 1, 2])) # [1, 2] # 使用None過濾假值 list(filter(None, [0, 1, False, True])) # [1, True] # 臨界值處理 list(filter(lambda x: x>0, [])) # []
9.55 reduce()
對(duì)元素進(jìn)行累積計(jì)算(需從functools導(dǎo)入)。
from functools import reduce # 基本用法 reduce(lambda x,y: x+y, [1,2,3,4]) # 10 (((1+2)+3)+4) # 指定初始值 reduce(lambda x,y: x+y, [1,2,3], 10) # 16 # 臨界值處理 reduce(lambda x,y: x+y, []) # TypeError: reduce() of empty sequence with no initial value reduce(lambda x,y: x+y, [1]) # 1 (單元素直接返回)
10. 模塊與包函數(shù)
10.56 import
導(dǎo)入模塊。
# 基本用法 # import math # math.sqrt(4) # 別名 # import numpy as np # 臨界值處理 # import nonexistent_module # ModuleNotFoundError
10.57 from…import
從模塊導(dǎo)入特定對(duì)象。
# 基本用法 # from math import sqrt # sqrt(4) # 導(dǎo)入多個(gè) # from math import sqrt, pi # 臨界值處理 # from math import nonexistent # ImportError: cannot import name 'nonexistent'
11. 日期時(shí)間函數(shù)
11.58 datetime.date.today()
獲取當(dāng)前日期。
from datetime import date # 基本用法 # today = date.today() # 返回date對(duì)象 # 臨界值處理 # 無參數(shù),總是返回當(dāng)前日期
11.59 datetime.datetime.now()
獲取當(dāng)前日期和時(shí)間。
from datetime import datetime # 基本用法 # now = datetime.now() # 返回datetime對(duì)象 # 指定時(shí)區(qū) # from datetime import timezone # datetime.now(timezone.utc) # 臨界值處理 # 無參數(shù),總是返回當(dāng)前時(shí)間
11.60 datetime.datetime.strptime()
將字符串解析為日期時(shí)間對(duì)象。
from datetime import datetime
# 基本用法
# dt = datetime.strptime('2023-01-01', '%Y-%m-%d')
# 臨界值處理
# datetime.strptime('invalid', '%Y') # ValueError: time data 'invalid' does not match format '%Y'
# datetime.strptime(None, '%Y') # TypeError: strptime() argument 1 must be str, not None
11.61 datetime.datetime.strftime()
將日期時(shí)間對(duì)象格式化為字符串。
from datetime import datetime
# 基本用法
# now = datetime.now()
# now.strftime('%Y-%m-%d %H:%M:%S')
# 臨界值處理
# datetime.strftime(None, '%Y') # AttributeError: 'NoneType' object has no attribute 'strftime'
12. 錯(cuò)誤處理函數(shù)
12.62 try-except
捕獲和處理異常。
# 基本用法
try:
1 / 0
except ZeroDivisionError:
print("不能除以零")
# 多個(gè)異常
try:
# 可能出錯(cuò)的代碼
except (TypeError, ValueError):
# 處理多種異常
except Exception as e:
# 捕獲所有異常
print(f"發(fā)生錯(cuò)誤: {e}")
finally:
# 無論是否發(fā)生異常都會(huì)執(zhí)行
print("清理代碼")
# 臨界值處理
# 空的try-except塊是合法但不好的做法
12.63 raise
手動(dòng)拋出異常。
# 基本用法
if x < 0:
raise ValueError("x不能為負(fù)數(shù)")
# 重新拋出當(dāng)前異常
try:
1 / 0
except:
print("發(fā)生錯(cuò)誤")
raise # 重新拋出
# 臨界值處理
raise # 不在except塊中使用會(huì)引發(fā)RuntimeError
raise None # TypeError: exceptions must derive from BaseException
13. 其他常用函數(shù)
13.64 id()
返回對(duì)象的唯一標(biāo)識(shí)符。
# 基本用法 x = 1 id(x) # 返回內(nèi)存地址 # 臨界值處理 id(None) # 返回None的id
13.65 type()
返回對(duì)象的類型。
# 基本用法
type(1) # <class 'int'>
type('a') # <class 'str'>
# 臨界值處理
type(None) # <class 'NoneType'>
type(type) # <class 'type'>
13.66 isinstance()
檢查對(duì)象是否是類的實(shí)例。
# 基本用法
isinstance(1, int) # True
isinstance('a', str) # True
# 檢查多個(gè)類型
isinstance(1, (int, float)) # True
# 臨界值處理
isinstance(1, type) # False
isinstance(int, type) # True
13.67 hasattr()
檢查對(duì)象是否有指定屬性。
# 基本用法
hasattr('abc', 'upper') # True
# 臨界值處理
hasattr(None, 'x') # False
hasattr(1, 'imag') # True (int有imag屬性)
13.68 setattr()
設(shè)置對(duì)象的屬性值。
# 基本用法 class MyClass: pass obj = MyClass() setattr(obj, 'x', 1) # obj.x = 1 # 臨界值處理 setattr(1, 'x', 1) # TypeError: 'int' object has no attribute 'x' setattr(obj, 123, 1) # 屬性名應(yīng)為字符串
13.69 getattr()
獲取對(duì)象的屬性值。
# 基本用法
getattr('abc', 'upper')() # 'ABC'
# 指定默認(rèn)值
getattr('abc', 'x', None) # None
# 臨界值處理
getattr('abc', 123) # TypeError: attribute name must be string
13.70 delattr()
刪除對(duì)象的屬性。
# 基本用法 class MyClass: x = 1 obj = MyClass() delattr(obj, 'x') # 臨界值處理 delattr(obj, 'x') # AttributeError: x delattr(1, 'real') # TypeError: 'int' object has no attribute 'real'
13.71 globals()
返回全局變量的字典。
# 基本用法 globals() # 返回當(dāng)前全局符號(hào)表 # 臨界值處理 # 總是返回字典,即使在函數(shù)內(nèi)部
13.72 locals()
返回局部變量的字典。
# 基本用法
def func():
x = 1
return locals()
func() # {'x': 1}
# 臨界值處理
# 在模塊級(jí)別,locals()和globals()相同
13.73 help()
啟動(dòng)幫助系統(tǒng)。
# 基本用法 # help(list) # 顯示list的幫助信息 # 臨界值處理 # help(None) # 顯示None的幫助信息
13.74 dir()
返回對(duì)象的屬性列表。
# 基本用法 dir(list) # 返回list的屬性和方法列表 # 臨界值處理 dir() # 返回當(dāng)前作用域的變量名 dir(None) # 返回None的屬性和方法列表
13.75 compile()
將字符串編譯為代碼對(duì)象。
# 基本用法
code = compile('print("hello")', 'test', 'exec')
exec(code) # 輸出hello
# 臨界值處理
compile('invalid code', 'test', 'exec') # SyntaxError
compile(123, 'test', 'exec') # TypeError: expected string without null bytes
13.76 eval()
計(jì)算字符串表達(dá)式的值。
# 基本用法
eval('1 + 1') # 2
# 臨界值處理
eval('import os') # SyntaxError
eval(None) # TypeError: eval() arg 1 must be a string, bytes or code object
13.77 exec()
執(zhí)行字符串或代碼對(duì)象中的代碼。
# 基本用法
exec('x = 1\nprint(x)') # 輸出1
# 臨界值處理
exec(None) # TypeError: exec() arg 1 must be a string, bytes or code object
13.78 hash()
返回對(duì)象的哈希值。
# 基本用法
hash('abc') # 返回哈希值
# 臨界值處理
hash([]) # TypeError: unhashable type: 'list'
hash(None) # 返回None的哈希值
13.79 iter()
返回迭代器對(duì)象。
# 基本用法 it = iter([1, 2, 3]) next(it) # 1 # 臨界值處理 iter(1) # TypeError: 'int' object is not iterable iter(None) # TypeError: 'NoneType' object is not iterable
13.80 next()
獲取迭代器的下一個(gè)元素。
# 基本用法 it = iter([1, 2]) next(it) # 1 # 指定默認(rèn)值 next(it, 'end') # 2 next(it, 'end') # 'end' # 臨界值處理 next(it) # StopIteration
13.81 all()
檢查可迭代對(duì)象中的所有元素是否為真。
# 基本用法 all([1, 2, 3]) # True all([1, 0, 3]) # False # 臨界值處理 all([]) # True (空可迭代對(duì)象) all([None]) # False
13.82 any()
檢查可迭代對(duì)象中是否有任何元素為真。
# 基本用法 any([0, 1, 0]) # True any([0, 0, 0]) # False # 臨界值處理 any([]) # False (空可迭代對(duì)象) any([None]) # False
13.83 bytes()
創(chuàng)建字節(jié)對(duì)象。
# 基本用法
bytes([1, 2, 3]) # b'\x01\x02\x03'
bytes('abc', 'utf-8') # b'abc'
# 臨界值處理
bytes(-1) # ValueError: negative count
bytes('abc', 'invalid') # LookupError: unknown encoding: invalid
13.84 bytearray()
創(chuàng)建可變的字節(jié)數(shù)組。
# 基本用法 bytearray([1, 2, 3]) # bytearray(b'\x01\x02\x03') # 臨界值處理 bytearray(-1) # ValueError: negative count
13.85 memoryview()
返回對(duì)象的內(nèi)存視圖。
# 基本用法
mv = memoryview(b'abc')
mv[0] # 97
# 臨界值處理
memoryview('abc') # TypeError: memoryview: a bytes-like object is required
13.86 ord()
返回字符的Unicode碼點(diǎn)。
# 基本用法
ord('a') # 97
# 臨界值處理
ord('') # TypeError: ord() expected a character, but string of length 0 found
ord('ab') # TypeError: ord() expected a character, but string of length 2 found
13.87 chr()
根據(jù)Unicode碼點(diǎn)返回字符。
# 基本用法 chr(97) # 'a' # 臨界值處理 chr(-1) # ValueError: chr() arg not in range(0x110000) chr(0x110000) # ValueError
13.88 bin()
將整數(shù)轉(zhuǎn)換為二進(jìn)制字符串。
# 基本用法 bin(10) # '0b1010' # 臨界值處理 bin(3.14) # TypeError: 'float' object cannot be interpreted as an integer bin(-10) # '-0b1010'
13.89 oct()
將整數(shù)轉(zhuǎn)換為八進(jìn)制字符串。
# 基本用法 oct(8) # '0o10' # 臨界值處理 oct(3.14) # TypeError oct(-8) # '-0o10'
13.90 hex()
將整數(shù)轉(zhuǎn)換為十六進(jìn)制字符串。
# 基本用法 hex(16) # '0x10' # 臨界值處理 hex(3.14) # TypeError hex(-16) # '-0x10'
13.91 frozenset()
創(chuàng)建不可變集合。
# 基本用法 fs = frozenset([1, 2, 3]) # 臨界值處理 frozenset(None) # TypeError: 'NoneType' object is not iterable
13.92 super()
調(diào)用父類方法。
# 基本用法
class Parent:
def method(self):
print("Parent method")
class Child(Parent):
def method(self):
super().method()
print("Child method")
Child().method()
# 輸出:
# Parent method
# Child method
# 臨界值處理
# 不正確的使用會(huì)導(dǎo)致RuntimeError
13.93 property()
創(chuàng)建屬性描述符。
# 基本用法
class MyClass:
def __init__(self):
self._x = None
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
obj = MyClass()
obj.x = 1 # 調(diào)用setter
print(obj.x) # 調(diào)用getter
# 臨界值處理
# 不正確的屬性訪問會(huì)引發(fā)AttributeError
13.94 classmethod()
定義類方法。
# 基本用法
class MyClass:
@classmethod
def class_method(cls):
print(f"Called from {cls}")
MyClass.class_method() # 通過類調(diào)用
obj = MyClass()
obj.class_method() # 通過實(shí)例調(diào)用
# 臨界值處理
# 不正確的使用會(huì)導(dǎo)致TypeError
13.95 staticmethod()
定義靜態(tài)方法。
# 基本用法
class MyClass:
@staticmethod
def static_method():
print("Static method")
MyClass.static_method() # 通過類調(diào)用
obj = MyClass()
obj.static_method() # 通過實(shí)例調(diào)用
# 臨界值處理
# 不正確的使用會(huì)導(dǎo)致TypeError
13.96 len()
返回對(duì)象的長(zhǎng)度或元素個(gè)數(shù)。
# 基本用法
len('abc') # 3
len([1,2,3]) # 3
# 臨界值處理
len(123) # TypeError
len(None) # TypeError
13.97 sorted()
對(duì)可迭代對(duì)象進(jìn)行排序并返回新列表。
# 基本用法 sorted([3, 1, 2]) # [1, 2, 3] # 指定key和reverse sorted(['apple', 'banana'], key=len, reverse=True) # ['banana', 'apple'] # 臨界值處理 sorted(None) # TypeError sorted([1, 'a']) # TypeError
13.98 reversed()
返回反轉(zhuǎn)的迭代器。
# 基本用法 list(reversed([1, 2, 3])) # [3, 2, 1] # 臨界值處理 list(reversed(None)) # TypeError list(reversed(123)) # TypeError
13.99 format()
格式化字符串。
# 基本用法
format(3.14159, '.2f') # '3.14'
"{:.2f}".format(3.14159) # '3.14'
# 臨界值處理
format('abc', 123) # TypeError
13.100 vars()
返回對(duì)象的屬性字典。
# 基本用法
class MyClass: pass
obj = MyClass()
obj.x = 1
vars(obj) # {'x': 1}
# 臨界值處理
vars(1) # TypeError
vars(None) # TypeError
總結(jié)
到此這篇關(guān)于Python中100個(gè)常用函數(shù)用法全面解析的文章就介紹到這了,更多相關(guān)Python 100個(gè)常用函數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)字典按key或者value進(jìn)行排序操作示例【sorted】
這篇文章主要介紹了Python實(shí)現(xiàn)字典按key或者value進(jìn)行排序操作,結(jié)合實(shí)例形式分析了Python針對(duì)字典按照key或者value進(jìn)行排序的相關(guān)操作技巧,需要的朋友可以參考下2019-05-05
基于Python實(shí)現(xiàn)自動(dòng)化生成數(shù)據(jù)報(bào)表
這篇文章主要介紹了如何使用Python自動(dòng)化生成數(shù)據(jù)報(bào)表,從而提高效率,再也不用一條條數(shù)據(jù)創(chuàng)建Excel數(shù)據(jù)報(bào)表了,感興趣的同學(xué)可以試一試2022-01-01
scrapy 遠(yuǎn)程登錄控制臺(tái)的實(shí)現(xiàn)
本文主要介紹了scrapy 遠(yuǎn)程登錄控制臺(tái)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
python3中超級(jí)好用的日志模塊-loguru模塊使用詳解
loguru默認(rèn)的輸出格式是上面的內(nèi)容,有時(shí)間、級(jí)別、模塊名、行號(hào)以及日志信息,不需要手動(dòng)創(chuàng)建?logger,直接使用即可,另外其輸出還是彩色的,看起來會(huì)更加友好,這篇文章主要介紹了python3中超級(jí)好用的日志模塊-loguru模塊使用詳解,需要的朋友可以參考下2022-11-11
Python try except異常捕獲機(jī)制原理解析
這篇文章主要介紹了Python try except異常捕獲機(jī)制原理解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
Python采用socket模擬TCP通訊的實(shí)現(xiàn)方法
這篇文章主要介紹了Python采用socket模擬TCP通訊的實(shí)現(xiàn)方法,程序分為TCP的server端與client端兩部分,分別對(duì)這兩部分進(jìn)行了較為深入的分析,需要的朋友可以參考下2014-11-11
在Python中使用AOP實(shí)現(xiàn)Redis緩存示例
本篇文章主要介紹了在Python中使用AOP實(shí)現(xiàn)Redis緩存示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07
淺談keras中Dropout在預(yù)測(cè)過程中是否仍要起作用
這篇文章主要介紹了淺談keras中Dropout在預(yù)測(cè)過程中是否仍要起作用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07
Python如何使用qrcode生成指定內(nèi)容的二維碼并在GUI界面顯示
現(xiàn)在二維碼很流行,大街小巷大小商品廣告上的二維碼標(biāo)簽都隨處可見,下面這篇文章主要給大家介紹了關(guān)于如何使用qrcode生成指定內(nèi)容的二維碼并在GUI界面顯示的相關(guān)資料,需要的朋友可以參考下2022-09-09

