整數和浮點(Python3 沒有int和long只有int類型)
十進制 默認
二進制 0bnnn
八進制 0onnn
十六進制 0xnnn
float() decimal 固定小數模塊
fractions有理分數
Bool類型 Ture False
bool()默認False
and or not 不支持xor
& l ^ ~(or)
<< >> 二進制移位
None 空對象(唯一的)
不可調用
容器內型
可迭代的類型
字符串 單重 雙重 三重 引號
字符串不可變,基於當年字符串重新創建字符串,指向新的地址
uppper lower capitalize
center ljust rjust 對齊方式
startwith endwith
find index rfind
isalpha isdigit isalnum
join
split splitlines partition 分割
strip lstrip rstrip 出去指定字符默認除去空格,全局replace
replace
format
字節和字節數組
byte bytearry
1、列表、元組操作
定義列表
list1=[] list2=['a','bit','clor'] list3=[none]*5
列表的元素訪問
>>> list2=['a','bit','colr','doll','esr','fire'] >>> list2=['a','bit','colr','doll','esr','fire'] >>> list2[0] #0爲第一個 'a' >>> list2[-1] #-1爲倒數第一個 'fire'>>> list2[-2] 'esr' >>> list2[0:] #0開始取完,由於是開區間,右邊就不能寫-1,不然取不完 ['a', 'bit', 'colr', 'doll', 'esr', 'fire'] >>> list2[:-2] #第一個到倒數第二個,不包含倒數第二個,左閉右開的區間 ['a', 'bit', 'colr', 'doll'] >>> list2[::2] #步長爲2 ['a', 'colr', 'esr']
基本方法:
增加
list.append()
>>> list2.append('thisisappendin') >>> list2 ['a', 'bit', 'colr', 'doll', 'esr', 'fire', 'thisisappendin']
list.insert("positon",'')
>>> list2.insert(2,'inse') >>> list2 ['a', 'bit', 'inse', 'colr', 'doll', 'esr', 'fire', 'thisisappendin']
刪除
del list
>>> del list2 >>> list2 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'list2' is not defined >>> list2=['a', 'bit', 'inse', 'colr', 'doll', 'esr', 'fire', 'thisisappendin'] >>> del list2[2] >>> list2 ['a', 'bit', 'colr', 'doll', 'esr', 'fire', 'thisisappendin']
list.pop(下標)
>>> list2.pop(2) #不加位置參數,默認最後一個 'colr' >>> list2 ['a', 'bit', 'doll', 'esr', 'fire', 'thisisappendin'] list.remove('value') >>> list2.remove('doll') >>> list2 ['a', 'bit', 'esr', 'fire', 'thisisappendin']
索引
list.index() 返回第一個匹配到的
>>> list2 ['a', 'bit', 'esr', 'fire', 'thisisappendin'] >>> list2.index('esr') 2
list.clear()
>>> list1=[1,2,3,4,5,6] >>> list2=['a','b','c','d','e'] >>> list3=list1 >>> list3 [1, 2, 3, 4, 5, 6] >>> list3.clear <built-in method clear of list object at 0x7fd9f2eb04c8> >>> list1 [1, 2, 7, 4, 5, 6]
list.sort() python3不支持同時有字符串和數字進行排序
list.reverse() 翻轉
list.count("")
list.extend(list2) 把list2的內容擴展到list1
list.copy() 淺copy
>>> list1=[1,2,3,45,6] >>> list2=list1.copy() >>> list2 [1, 2, 3, 45, 6] >>> list2 [1, 2, 3, 45, 6] >>> list1[2]=111 >>> list2 [1, 2, 3, 45, 6] >>> del list1 >>> del list2 >>> list1=[[1,2,3,4],121,['a',1,'x'],{'x':20,'pm':15}] >>> list2=list1.copy() >>> list1[1]=12580 >>> list1 [[1, 2, 3, 4], 12580, ['a', 1, 'x'], {'pm': 15, 'x': 20}] >>> list2 [[1, 2, 3, 4], 121, ['a', 1, 'x'], {'pm': 15, 'x': 20}] >>> list1[0][2]=66 >>> list1 [[1, 2, 66, 4], 12580, ['a', 1, 'x'], {'pm': 15, 'x': 20}] >>> list2 [[1, 2, 66, 4], 121, ['a', 1, 'x'], {'pm': 15, 'x': 20}]
淺copy只拷貝一層,只是複製一層值,而當這層值是一個引用時,複製的是引用,他們指向的同一個內存對象,這個對象並沒有複製,這是後,修改其中一個另外一個也跟隨改變