Python內(nèi)置函數(shù)(1)— abs()、all()、any()、ascii()、bin()、bool()、breakpoint()、bytearray()、bytes()、callable()。
Python內(nèi)置函數(shù)(2)— chr()、classmethod()、compile()、complex()、delattr()、dict()、dir()、divmod()、enumerate()、eval()。
Python內(nèi)置函數(shù)(3)— exec()、filter()、float()、format()、frozenset()、getattr()、globals()、hasattr()、hash()、help()。
Python內(nèi)置函數(shù)(4)— hex()、id()、input()、int()、isinstance()、issubclass、iter()、len()、list()、locals()。
Python內(nèi)置函數(shù)(5)— map()、max()、memoryview()、min()、next()、object()、oct()、open()、ord()、pow()。
Python內(nèi)置函數(shù)(6)— print()、property()、range()、repr()、reversed()、round()、set()、setattr()、slice()、sorted()。
Python內(nèi)置函數(shù)(7)— staticmethod()、str()、sum()、super()、tuple()、type()、vars()、zip()、__import__()。

21、exec()
a)描述
原文:
Execute the given source in the context of globals and locals.
The source may be a string representing one or more Python statements or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
中文:
在全局變量和局部變量上下文中執(zhí)行給定的源。
源可以是表示一個或多個Python語句的字符串,也可以是compile()返回的代碼對象。
全局變量必須是字典,局部變量可以是任何映射,默認(rèn)為當(dāng)前全局變量和局部變量。
如果只提供全局變量,則局部變量默認(rèn)為全局變量。
詮釋:
exec 執(zhí)行儲存在字符串或文件中的 Python 語句,相比于 eval,exec可以執(zhí)行更復(fù)雜的 Python 代碼。
b)語法
exec 的語法:exec(object[, globals[, locals]])
c)參數(shù)
object:必選參數(shù),表示需要被指定的Python代碼。它必須是字符串或code對象。如果object是一個字符串,該字符串會先被解析為一組Python語句,然后在執(zhí)行(除非發(fā)生語法錯誤)。如果object是一個code對象,那么它只是被簡單的執(zhí)行。
globals:可選參數(shù),表示全局命名空間(存放全局變量),如果被提供,則必須是一個字典對象。
locals:可選參數(shù),表示當(dāng)前局部命名空間(存放局部變量),如果被提供,可以是任何映射對象。如果該參數(shù)被忽略,那么它將會取與globals相同的值。
d)返回值
exec 返回值永遠(yuǎn)為 None。
e)實例
實例1:
exec('print("Hello World!")')
# 單行語句字符串
exec("print ('kevin.com')")
# 多行語句字符串
exec("""for i in range(5):
print ("iter time: %d" % i)
""")
運行結(jié)果:
Hello World!
kevin.com
iter time: 0
iter time: 1
iter time: 2
iter time: 3
iter time: 4
實例2:
x = 10
expr = """
z = 30
sum = x + y + z
print(sum)
"""
def func():
y = 20
exec(expr)
exec(expr, {'x': 1, 'y': 2})
exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})
func()
運行結(jié)果:
60
33
34
22、filter()
a)描述
原文:
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.
中文:
filter(function or None, iterable)——> filter object
返回一個迭代器,該迭代器產(chǎn)生的iterable項對應(yīng)的函數(shù)(項)為真。如果function為None,則返回為True的項。
詮釋:
filter() 函數(shù)用于過濾序列,過濾掉不符合條件的元素,返回一個迭代器對象,如果要轉(zhuǎn)換為列表,可以使用 list() 來轉(zhuǎn)換。
該接收兩個參數(shù),第一個為函數(shù),第二個為序列,序列的每個元素作為參數(shù)傳遞給函數(shù)進行判,然后返回 True 或 False,最后將返回 True 的元素放到新列表中。
b)語法
filter() 方法的語法:filter(function, iterable)
c)參數(shù)
function:判斷函數(shù)。
iterable:可迭代對象。
d)返回值
返回一個迭代器對象。
e)實例
實例1(過濾出列表中的所有奇數(shù)):
def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)
運行結(jié)果:
[1, 3, 5, 7, 9]
實例2(過濾出1~100中平方根是整數(shù)的數(shù)):
import math
def is_sqr(x):
return math.sqrt(x) % 1 == 0
tmplist = filter(is_sqr, range(1, 101))
newlist = list(tmplist)
print(newlist)
運行結(jié)果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
23、float()
a)描述
float() 函數(shù)用于將整數(shù)和字符串轉(zhuǎn)換成浮點數(shù)。
b)語法
float()方法的語法:class float([x])
c)參數(shù)
x:整數(shù)或字符串。
d)返回值
返回浮點數(shù)。
e)實例
print("float(1):",float(1))
print("float(112):",float(112))
print("float(-123.6):",float(-123.6))
print("float('123'):",float('123')) # 字符串
運行結(jié)果:
float(1): 1.0
float(112): 112.0
float(-123.6): -123.6
float('123'): 123.0
24、format()
a)描述
原文:
Return value.__format__(format_spec)
format_spec defaults to the empty string.
See the Format Specification Mini-Language section of help('FORMATTING') for details.
中文:
返回value.__format__(format_spec)
format_spec默認(rèn)為空字符串。
有關(guān)詳細(xì)信息,請參閱幫助(“FORMATTING”)的格式規(guī)范Mini-Language部分。
詮釋:
format()增強了字符串格式化的功能,基本語法是通過 {} 和 : 來代替以前的 %,format 函數(shù)可以接受不限個參數(shù),位置可以不按順序。
實例(str.format() 格式化數(shù)字):
print("{:.2f}".format(3.1415926))
運行結(jié)果:
3.14
| 數(shù)字 | 格式 | 輸出 | 描述 |
|---|---|---|---|
| 3.1415926 | {:.2f} | 3.14 | 保留小數(shù)點后兩位 |
| 3.1415926 | {:+.2f} | +3.14 | 帶符號保留小數(shù)點后兩位 |
| -1 | {:+.2f} | -1.00 | 帶符號保留小數(shù)點后兩位 |
| 2.71828 | {:.0f} | 3 | 不帶小數(shù) |
| 5 | {:0>2d} | 05 | 數(shù)字補零 (填充左邊, 寬度為2) |
| 5 | {:x<4d} | 5xxx | 數(shù)字補x (填充右邊, 寬度為4) |
| 10 | {:x<4d} | 10xx | 數(shù)字補x (填充右邊, 寬度為4) |
| 1000000 | {:,} | 1,000,000 | 以逗號分隔的數(shù)字格式 |
| 0.25 | {:.2%} | 25.00% | 百分比格式 |
| 1000000000 | {:.2e} | 1.00e+09 | 指數(shù)記法 |
| 13 | {:>10d} | 13 | 右對齊 (默認(rèn), 寬度為10) |
| 13 | {:<10d} | 13 | 左對齊 (寬度為10) |
| 13 | {:^10d} | 13 | 中間對齊 (寬度為10) |
| 11 | '{:b}'.format(11) '{:d}'.format(11) '{:o}'.format(11) '{:x}'.format(11) '{:#x}'.format(11) '{:#X}'.format(11) |
1011 11 13 b 0xb 0XB |
進制 |
^, <, > 分別是居中、左對齊、右對齊,后面帶寬度,: 號后面帶填充的字符,只能是一個字符,不指定則默認(rèn)是用空格填充。
+ 表示在正數(shù)前顯示 +,負(fù)數(shù)前顯示 -;(空格)表示在正數(shù)前加空格。
b、d、o、x 分別是二進制、十進制、八進制、十六進制。
說明:我們可以使用大括號 {} 來轉(zhuǎn)義大括號。
b)實例
實例1(可以接受不限個參數(shù),位置可以不按順序。):
print('"{} {}".format("hello", "world"):',"{} {}".format("hello", "world")) # 不設(shè)置指定位置,按默認(rèn)順序
print('"{0} {1}".format("hello", "world"):',"{0} {1}".format("hello", "world")) # 設(shè)置指定位置
print('"{1} {0} {1}".format("hello", "world"):',"{1} {0} {1}".format("hello", "world")) # 設(shè)置指定位置
運行結(jié)果:
"{} {}".format("hello", "world"): hello world
"{0} {1}".format("hello", "world"): hello world
"{1} {0} {1}".format("hello", "world"): world hello world
實例2(設(shè)置參數(shù)):
print("網(wǎng)站名:{name}, 地址: {url}".format(name="凱文超市", url="www.kevin.com"))
# 通過字典設(shè)置參數(shù)
site = {"name": "凱文超市", "url": "www.kevin.com"}
print("網(wǎng)站名:{name}, 地址: {url}".format(**site))
# 通過列表索引設(shè)置參數(shù)
my_list = ['凱文超市', 'www.kevin.com']
print("網(wǎng)站名:{0[0]}, 地址: {0[1]}".format(my_list)) # "0" 是必須的
運行結(jié)果:
網(wǎng)站名:凱文超市, 地址: www.kevin.com
網(wǎng)站名:凱文超市, 地址: www.kevin.com
網(wǎng)站名:凱文超市, 地址: www.kevin.com
實例3(向 str.format() 傳入對象):
class AssignValue(object):
def __init__(self, value):
self.value = value
my_value = AssignValue(6)
print('value為:{0.value}'.format(my_value)) # "0" 是可選的
運行結(jié)果:
value為:6
實例4(使用大括號 {} 來轉(zhuǎn)義大括號):
print ("{} 對應(yīng)的位置是 {{0}}".format("kevin"))
運行結(jié)果:
kevin 對應(yīng)的位置是 {0}
實例5(如果參數(shù)format_spec未提供,則和調(diào)用str(value)效果相同,轉(zhuǎn)換成字符串格式化):
>>> format(3.1415936)
'3.1415936'
>>> str(3.1415926)
'3.1415926'
實例6(對于不同的類型,參數(shù)format_spec可提供的值都不一樣):
#字符串可以提供的參數(shù),指定對齊方式,<是左對齊, >是右對齊,^是居中對齊
print(format('test', '<20'))
print(format('test', '>20'))
print(format('test', '^20'))
#整形數(shù)值可以提供的參數(shù)有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
>>> format(3,'b') #轉(zhuǎn)換成二進制
'11'
>>> format(97,'c') #轉(zhuǎn)換unicode成字符
'a'
>>> format(11,'d') #轉(zhuǎn)換成10進制
'11'
>>> format(11,'o') #轉(zhuǎn)換成8進制
'13'
>>> format(11,'x') #轉(zhuǎn)換成16進制 小寫字母表示
'b'
>>> format(11,'X') #轉(zhuǎn)換成16進制 大寫字母表示
'B'
>>> format(11,'n') #和d一樣
'11'
>>> format(11) #默認(rèn)和d一樣
'11'
#浮點數(shù)可以提供的參數(shù)有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
>>> format(314159267,'e') #科學(xué)計數(shù)法,默認(rèn)保留6位小數(shù)
'3.141593e+08'
>>> format(314159267,'0.2e') #科學(xué)計數(shù)法,指定保留2位小數(shù)
'3.14e+08'
>>> format(314159267,'0.2E') #科學(xué)計數(shù)法,指定保留2位小數(shù),采用大寫E表示
'3.14E+08'
>>> format(314159267,'f') #小數(shù)點計數(shù)法,默認(rèn)保留6位小數(shù)
'314159267.000000'
>>> format(3.14159267000,'f') #小數(shù)點計數(shù)法,默認(rèn)保留6位小數(shù)
'3.141593'
>>> format(3.14159267000,'0.8f') #小數(shù)點計數(shù)法,指定保留8位小數(shù)
'3.14159267'
>>> format(3.14159267000,'0.10f') #小數(shù)點計數(shù)法,指定保留10位小數(shù)
'3.1415926700'
>>> format(3.14e+1000000,'F') #小數(shù)點計數(shù)法,無窮大轉(zhuǎn)換成大小字母
'INF'
#g的格式化比較特殊,假設(shè)p為格式中指定的保留小數(shù)位數(shù),先嘗試采用科學(xué)計數(shù)法格式化,得到冪指數(shù)exp,如果-4<=exp<p,則采用小數(shù)計數(shù)法,并保留p-1-exp位小數(shù),否則按小數(shù)計數(shù)法計數(shù),并按p-1保留小數(shù)位數(shù)
>>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學(xué)計數(shù)法計數(shù),保留0位小數(shù)點
'3e-05'
>>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學(xué)計數(shù)法計數(shù),保留1位小數(shù)點
'3.1e-05'
>>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學(xué)計數(shù)法計數(shù),保留2位小數(shù)點
'3.14e-05'
>>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學(xué)計數(shù)法計數(shù),保留0位小數(shù)點,E使用大寫
'3.14E-05'
>>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數(shù)計數(shù)法計數(shù),保留0位小數(shù)點
'3'
>>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數(shù)計數(shù)法計數(shù),保留1位小數(shù)點
'3.1'
>>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數(shù)計數(shù)法計數(shù),保留2位小數(shù)點
'3.14'
>>> format(0.00003141566,'.1n') #和g相同
'3e-05'
>>> format(0.00003141566,'.3n') #和g相同
'3.14e-05'
>>> format(0.00003141566) #和g相同
'3.141566e-05'
25、frozenset()
a)描述
frozenset() 返回一個凍結(jié)的集合,凍結(jié)后集合不能再添加或刪除任何元素。
b)語法
frozenset() 函數(shù)語法:class frozenset([iterable])
c)參數(shù)
iterable:可迭代的對象,比如列表、字典、元組等等。
d)返回值
返回新的 frozenset 對象,如果不提供任何參數(shù),默認(rèn)會生成空集合。
e)實例
a = frozenset(range(10)) # 生成一個新的不可變集合
print("a:",a)
b = frozenset('kevin') # 創(chuàng)建不可變集合
print("b:",b)
運行結(jié)果:
a: frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
b: frozenset({'e', 'k', 'n', 'v', 'i'})
26、getattr()
a)描述
原文:
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case.
中文:
getattr(object, name[, default])—>value
從對象中獲取命名屬性;getattr(x, 'y')等于x.y。
當(dāng)給定默認(rèn)參數(shù)時,當(dāng)屬性不存在時返回;否則,在這種情況下會引發(fā)異常。
詮釋:
getattr() 函數(shù)用于返回一個對象屬性值。
b)語法
getattr 語法:getattr(object, name[, default])
c)參數(shù)
object:對象。
name:字符串,對象屬性。
default:默認(rèn)返回值,如果不提供該參數(shù),在沒有對應(yīng)屬性時,將觸發(fā) AttributeError。
d)返回值
返回對象屬性值。
e)實例
實例1:
class A(object):
bar = 1
a = A()
print("getattr(a, 'bar'):",getattr(a, 'bar')) # 獲取屬性 bar 值
print("getattr(a, 'bar2', 3):",getattr(a, 'bar2', 3)) # 屬性 bar2 不存在,但設(shè)置了默認(rèn)值
# print("getattr(a, 'bar2'):",getattr(a, 'bar2')) # 屬性 bar2 不存在,觸發(fā)異常
運行結(jié)果:
getattr(a, 'bar'): 1
getattr(a, 'bar2', 3): 3
Traceback (most recent call last):
File "D:/Python_Project/Temp.py", line 1166, in <module>
print("getattr(a, 'bar2'):",getattr(a, 'bar2')) # 屬性 bar2 不存在,觸發(fā)異常
AttributeError: 'A' object has no attribute 'bar2'
實例2:
class A(object):
def set(self, a, b):
x = a
a = b
b = x
print("a = {}, b = {}".format(a, b))
a = A()
c = getattr(a, 'set')
c(a='1', b='2')
運行結(jié)果:
a = 2, b = 1
27、globals()
a)描述
原文:
Return the dictionary containing the current scope's global variables.
NOTE: Updates to this dictionary will affect name lookups in the current global scope and vice-versa.
中文:
返回包含當(dāng)前作用域的全局變量的字典。
注意:這個字典的更新將影響當(dāng)前全局范圍內(nèi)的名稱查找,反之亦然。
b)語法
globals() 函數(shù)語法:globals()
c)參數(shù)
無
d)返回值
返回全局變量的字典。
e)實例
a = 'kevin'
print(globals()) # globals 函數(shù)返回一個全局變量的字典,包括所有導(dǎo)入的變量。
運行結(jié)果:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000212788A0970>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/Python_Project/Temp.py', '__cached__': None, 'a': 'kevin'}
28、hasattr()
a)描述
原文:
Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError.
中文:
返回對象是否具有給定名稱的屬性。
這是通過調(diào)用getattr(obj, name)捕獲AttributeError。
b)語法
hasattr 語法:hasattr(object, name)
c)參數(shù)
object:對象。
name:字符串,屬性名。
d)返回值
如果對象有該屬性返回 True,否則返回 False。
e)實例
class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
print("hasattr(point1, 'x'):",hasattr(point1, 'x'))
print("hasattr(point1, 'y'):",hasattr(point1, 'y'))
print("hasattr(point1, 'z'):",hasattr(point1, 'z'))
print("hasattr(point1, 'no'):",hasattr(point1, 'no')) # 沒有該屬性
運行結(jié)果:
hasattr(point1, 'x'): True
hasattr(point1, 'y'): True
hasattr(point1, 'z'): True
hasattr(point1, 'no'): False
29、hash()
a)描述
原文:
Return the hash value for the given object.
Two objects that compare equal must also have the same hash value, but the reverse is not necessarily true.
中文:
返回給定對象的哈希值。
兩個比較相等的對象也必須具有相同的哈希值,但反過來不一定正確。
詮釋:
hash() 函數(shù)可以應(yīng)用于數(shù)字、字符串和對象,不能直接應(yīng)用于 list、set、dictionary。
在 hash() 對對象使用時,所得的結(jié)果不僅和對象的內(nèi)容有關(guān),還和對象的 id(),也就是內(nèi)存地址有關(guān)。
hash() 函數(shù)的對象字符不管有多長,返回的 hash 值都是固定長度的,也用于校驗程序在傳輸過程中是否被第三方(木馬)修改,如果程序(字符)在傳輸過程中被修改hash值即發(fā)生變化,如果沒有被修改,則 hash 值和原始的 hash 值吻合,只要驗證 hash 值是否匹配即可驗證程序是否帶木馬(病毒)。
b)語法
hash 語法:hash(object)
c)參數(shù)
object -- 對象。
d)返回值
返回對象的哈希值。
e)實例
實例1:
print("hash('test'):",hash('test')) # 字符串
print("hash(1):",hash(1)) # 數(shù)字
print("hash(str([1,2,3])):",hash(str([1,2,3]))) # 集合
print("hash(str(sorted({'1':1}))):",hash(str(sorted({'1':1})))) # 字典
運行結(jié)果:
hash('test'): 85748363395829820
hash(1): 1
hash(str([1,2,3])): -1739346109313768372
hash(str(sorted({'1':1}))): 4803048949047724432
實例2:
class Test:
def __init__(self, i):
self.i = i
for i in range(10):
t = Test(1)
print(hash(t), id(t))
運行結(jié)果:
162349547608 2597592761728
162349529977 2597592479632
162349547608 2597592761728
162349529977 2597592479632
162349547608 2597592761728
162349529977 2597592479632
162349547608 2597592761728
162349529977 2597592479632
162349547608 2597592761728
162349529977 2597592479632
實例3:
name1='正常程序代碼'
name2='正常程序代碼帶病毒'
print("hash(name1):",hash(name1))
print("hash(name2):",hash(name2))
運行結(jié)果:
hash(name1): -6174195686864483401
hash(name2): 8746497541882159753
30、help()
a)描述
原文:
Define the builtin 'help'.
This is a wrapper around pydoc.help that provides a helpful message when 'help' is typed at the Python interactive prompt.
Calling help() at the Python prompt starts an interactive help session.
Calling help(thing) prints help for the python object 'thing'.
中文:
定義構(gòu)建“幫助”。
這是pydoc的包裝。在Python交互式提示符中鍵入“help”時提供有用信息的幫助。
在Python提示符下調(diào)用help()啟動交互式幫助會話。
調(diào)用help(thing)打印python對象“thing”的幫助。
b)語法
help 語法:help([object])
c)參數(shù)
object:對象。
d)返回值
返回對象幫助信息。
e)實例
help('sys') # 查看 sys 模塊的幫助
help('str') # 查看 str 數(shù)據(jù)類型的幫助
a = [1, 2, 3]
help(a) # 查看列表 list 幫助信息
help(a.append) # 顯示list的append方法的幫助
運行結(jié)果:
……顯示幫助信息……(此處省略)