1. 程式人生 > >python內置方法總結

python內置方法總結

hash 文件中 數通 返回值 fse 文件讀寫 byte nds 十進制轉二進制

技術分享圖片

# 註意:內置函數id()可以返回一個對象的身份,返回值為整數。這個整數通常對應與該對象在內存中的位置,但這與python的具體實現有關,不應該作為對身份的定義,即不夠精準,最精準的還是以內存地址為準。
# is運算符用於比較兩個對象的身份,等號比較兩個對象的值,內置函數type()則返回一個對象的類型

以下優先列出需要掌握的內置函數
print(abs(-1))  # 1  取絕對值

print(all([2, 3, 4, ‘sss‘, ‘True‘])) # 裏面的值全為Ture,則返回True,如果裏面的的值為空也返回True
print(any(‘3‘))      #裏面的值只要有一個為Ture,擇返回True,如果裏面的值為空,則返回False

print(bytes(‘你好,albert‘, encoding=‘utf-8‘)) # 把utf-8編碼的字符串轉化為二進制
print(callable(‘d‘.strip)) # 判斷裏面的值是不是可叠代類型 後面可以加()的都是,比如‘abc’.strip() 、 max() 等等

print(bin(11)) #十進制轉二進制
print(oct(11)) #十進制轉八進制
print(hex(11)) #十進制轉十六進制

print(bool(0)) #0,None,空的布爾值為假

res=‘你好egon‘.encode(‘utf-8‘) # unicode按照utf-8進行編碼,得到的結果為bytes類型
res=bytes(‘你好egon‘,encoding=‘utf-8‘) # 同上
print(res)

def func():
pass
print(callable(‘aaaa‘.strip)) #判斷某個對象是否是可以調用的,可調用指的是可以加括號執行某個功能

print(chr(90)) #按照ascii碼表將十進制數字轉成字符
print(ord(‘Z‘)) #按照ascii碼表將字符轉成十進制數字

print(dir(‘abc‘)) # 查看某個對象下可以用通過點調用到哪些方法
輸出:

[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘capitalize‘, ‘casefold‘, ‘center‘, ‘count‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘, ‘format_map‘, ‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdecimal‘, ‘isdigit‘, ‘isidentifier‘, ‘islower‘, ‘isnumeric‘, ‘isprintable‘, ‘isspace‘, ‘istitle‘, ‘isupper‘, ‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘, ‘maketrans‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]

print(divmod(1311,25)) # 輸出一個元祖,包含商和余數 (52,11)

eval 重點介紹,可用於文件讀寫操作
# 將字符內的表達式拿出運行一下,並拿到該表達式的執行結果
res=eval(‘{"name":"egon","age":18}‘)
print(res,type(res))
輸出:{‘name‘: ‘egon‘, ‘age‘: 18} <class ‘dict‘>
# eval 在文件中的應用
with open(‘db.txt‘,‘r‘,encoding=‘utf-8‘) as f:
s=f.read()
dic=eval(s)
print(dic,type(dic))
print(dic[‘egon‘])
# eval 可以吧默認文件打開得到的字符串表達式拿出來運行一下,並拿到表達式的執行結果, 轉化成原本的數據類型,進而更方便進行讀寫操作

fset=frozenset({1,2,3})  #集合是一個可變類型,frozenset可以制造不可變集合,fset已沒有.add方法。

print(len({‘x‘:1,‘y‘:2})) #{‘x‘:1,‘y‘:2}.__len__()

obj=iter(‘egon‘) #‘egon‘.__iter__()
print(next(obj)) #obj.__next__()
print(next(obj))#obj.__next__()
print(iter(obj))#obj.__next__()

輸出結果

2
e
g
<str_iterator object at 0x00000000021E7160>





python內置方法總結