Python入門篇-基礎數據類型之整型(int),字符串(str),字節(bytes),列表(list)和切片(slice)
作者:尹正傑
版權聲明:原創作品,謝絕轉載!否則將追究法律責任。
一.Python內置數據結構分類
1>.數值型
如 :int,float,complex,bool
2>.序列對象
字符串:str
列表:list
元組:tuple
3>.鍵值對
集合:set
字典:dict
二.數值型
1>.數值型概述
int、float、complex、bool都是class,1、5.0、2+3j都是對象即實例。
int:
python3的int就是長整型,且沒有大小限制,受限於內存區域的大小。
float:
有整數部分和小數部分組成。支持十進制和科學計數法表示。只有雙精度型。
complex:
有實數和虛數部分組成,實數和虛數部分都是浮點數,3+4.2J。
bool:
int的子類,僅有2個實例True、False對應1和0,可以和整數直接運算。
2>.類型轉換
int(x) 返回一個整數 float(x) 返回一個浮點數 complex(x)、complex(x,y) 返回一個復數 bool(x) 返回布爾值,前面講過False等價的對象
3>.數字的處理函數
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com import math #取整 print(math.floor(3.1)) print(math.floor(3.6)) #取整並加1 print(math.ceil(5.1)) print(math.ceil(5.6)) #查看PI的值 print(math.pi) #查看自然常數 print(math.e) #四舍六入,五往偶數靠攏,並非四舍五入.簡稱:“四舍六入五取偶” print(round(13.1)) print(round(13.6)) print(round(23.5)) print(round(26.5)) #取最小值 print(min(10,20)) #取最大值 print(max(100,200)) #取平方數 print(pow(5,2)) #二進制表示10 print(bin(10)) #八進制表示10 print(oct(10)) #十六進制表示10 print(hex(10))

3 3 6 6 3.141592653589793 2.718281828459045 13 14 24 26 10 200 25 0b1010 0o12 0xa
4>.類型判斷
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com #定義變量 Name = "Jason Yin" Age = 18 #判斷數據的類型 print(type(Name)) print(type(Age)) print(type(1+True)) print(type(1+True+2.0)) #查看變量的類型 print(type(Name) == str) print(type(Age) == int) #內置斷言操作 print(isinstance(Name,str)) print(isinstance(Age,int)) print(isinstance(100,str)) print(isinstance(100,(str,bool,int)))

<class 'str'> <class 'int'> <class 'int'> <class 'float'> True True True True False True
三.列表(list)
1>.列表概述
一個隊列,一個排列整齊的隊伍
列表內的個體稱作元素,由若干元素組成列表
元素可以是任意對象(數字、字符串、對象、列表等)
列表內元素有順序,可以使用索引
線性的數據結構
使用[ ] 表示
列表是可變的
請自行查閱資料了解:列表(List)、鏈表(Linked List)、隊列(Queue)、棧(Stack)的差異,我大致總結了下這幾種數據結構特點:
列表(List):在內存空間中是連續地址,查詢速度快,修改也快,但不利於頻繁新增或刪除元素(需要注意的是,隊尾新增或者刪除元素並不影響性能)。
鏈表(Linked List):在內存空間中是不連續地址,查詢速度慢,但利於頻繁新增或刪除元素。
隊列(Queue):其實我們有時候發現他和列表很像,但是不支持像列表那樣進行修改,First Input First Output(FIFO)簡單說就是指先進先出。就好像我們上班時候進地鐵站的時候,拍了很長的隊伍,有欄桿圍着人群,因此基本上沒人插隊。
棧(Stack):類似於我們小時候玩槍的上子彈操作,我們會發現先上子彈卻最后才能打出去,即Last In First Out 后進先出法(簡稱LIFO,即先進后出)。
2>.列表list定義,初始化
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ list() ----> new entry list list(iterable) ----> new list initalized from iterable's items 列表不能一開始就定義大小 """ list_1 = list() list_2 = [] list_3 = ["100","Jason Yin","5.21",[1,3,5,7,9]] list_4 = list(range(10)) print(list_1) print(list_2) print(list_3) print(list_4)

[] [] ['100', 'Jason Yin', '5.21', [1, 3, 5, 7, 9]] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3>. 列表索引訪問
索引,也叫下標 正索引:從左至右,從0開始,為列表中每一個元素編號 負索引:從右至左,從-1開始 正負索引不可以超界,否則引發異常IndexError 為了理解方便,可以認為列表是從左至右排列的,左邊是頭部,右邊是尾部,左邊是下界,右邊是上界 列表通過索引訪問 list[index] ,index就是索引,使用中括號訪問,時間復雜度為O(1),隨着列表元素規模的增加,通過索引訪問元素的效率並不會降低!
4>.列表查詢
index(value,[start,[stop]])
通過值value,從指定區間查找列表內的元素是否匹配
匹配第一個就立即返回索引
匹配不到,拋出異常ValueError
隨着列表元素規模的增加,性能會逐漸下降,時間復雜度為O(n)。因為它設計到遍歷,因此該方法我們在生產環境中應該盡量少用!
count(value)
返回列表中匹配value的次數。該方法相比index來說,屬於完全的O(n),因為index方法匹配到第一個就立即返回索引,可能不會遍歷整個列表,但count方法必須遍歷整個列表,因此該方法也應該盡量少用!
時間復雜度
index和count方法都是O(n)
隨着列表數據規模的增大,而效率下降。
如何返回列表元素的個數?如何遍歷?如何設計高效?
len()

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com list_1 = ["100","Jason Yin","100","5.21","100",[1,3,5,7,9],"100","300","100"] #匹配索引,我們可以給該方法傳遞三個參數,查看源碼就知道第一個參數傳遞的是要查詢的值,第二個參數和第三個參數分別為查詢的起始位置和結束位置。 print(list_1.index("Jason Yin")) print(list_1.index("100")) print(list_1.index("100",1)) print(list_1.index("100",3)) print(list_1.index("100",5,7)) #統計某個值在該列表中出現的次數,該方法的時間復雜度為O(n) print(list_1.count("100")) #以上代碼運行結果如下: 1 0 2 4 6 5
5>.如何查看幫助
6>.列表元素修改
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' 索引訪問修改 list[index] = value 索引不要超界 ''' list_1 = [1,2,3,4,5] print(list_1) list_1[len(list_1)-1] = 100 print(list_1) #以上代碼執行結果如下: [1, 2, 3, 4, 5] [1, 2, 3, 4, 100]
7>.列表增加,插入元素

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' append(object) -> None 列表尾部追加元素,返回None 返回None就意味着沒有新的列表產生,就地修改 時間復雜度是O(1) ''' list_1 = [1,2,3,4,5] print(list_1) list_1.append(100) print(list_1) #以上代碼執行結果如下: [1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 100]

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' insert(index, object) -> None 在指定的索引index處插入元素object 返回None就意味着沒有新的列表產生,就地修改 時間復雜度是O(n) 索引能超上下界嗎? 超越上界,尾部追加 超越下界,頭部追加 ''' list_1 = [1,2,3,4,5] print(list_1) list_1.insert(2,300) print(list_1) #以上代碼執行結果如下: [1, 2, 3, 4, 5] [1, 2, 300, 3, 4, 5]

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' + -> list 連接操作,將兩個列表連接起來 產生新的列表,原列表不變 本質上調用的是__add__()方法 * -> list 重復操作,將本列表元素重復n次,返回新的列表 ''' list_1 = [1,2,3,4,5] list_2 = ["a","b","c","d","e"] print(list_1) print(list_2) print(list_1 * 3) print(list_1 + list_2) #以上代碼執行結果如下: [1, 2, 3, 4, 5] ['a', 'b', 'c', 'd', 'e'] [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 'e']

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' extend(iteratable) -> None 將可迭代對象的元素追加進來,返回None 就地修改 ''' list_1 = [1,2,3,4,5] list_2 = ["a","b","c","d","e"] print(list_1) print(list_2) list_1.extend(list_2) print(list_1) print(list_2) #以上代碼執行結果如下: [1, 2, 3, 4, 5] ['a', 'b', 'c', 'd', 'e'] [1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 'e'] ['a', 'b', 'c', 'd', 'e']
8>.列表刪除元素

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' remove(value) -> None 從左至右查找第一個匹配value的值,移除該元素,返回None 就地修改 效率? ''' list_1 = [1,2,3,4,5] print(list_1) list_1.remove(3) print(list_1) #以上代碼執行結果如下: [1, 2, 3, 4, 5] [1, 2, 4, 5]

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' pop([index]) -> item 不指定索引index,就從列表尾部彈出一個元素 指定索引index,就從索引處彈出一個元素,索引超界拋出IndexError錯誤 效率?指定索引的的時間復雜度?不指定索引呢? ''' list_1 = [1,2,3,4,5] print(list_1) list_1.pop() print(list_1) list_1.pop(2) print(list_1) #以上代碼執行結果如下: [1, 2, 3, 4, 5] [1, 2, 3, 4] [1, 2, 4]

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' clear() -> None 清除列表所有元素,剩下一個空列表 ''' list_1 = [1,2,3,4,5] print(list_1) list_1.clear() print(list_1) #以上代碼執行結果如下: [1, 2, 3, 4, 5] []
9>.列表的其他操作

1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 #EMAIL:y1053419035@qq.com 6 7 ''' 8 reverse() -> None 9 將列表元素反轉,返回None 10 就地修改 11 ''' 12 13 list_1 = [1,2,3,4,5] 14 print(list_1) 15 16 list_1.reverse() 17 print(list_1) 18 19 20 21 22 23 #以上代碼執行結果如下: 24 [1, 2, 3, 4, 5] 25 [5, 4, 3, 2, 1]

1 #!/usr/bin/env python 2 #_*_conding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie 5 6 7 ''' 8 sort(key=None, reverse=False) -> None 9 對列表元素進行排序,就地修改,默認升序 10 reverse為True,反轉,降序 11 key一個函數,指定key如何排序,key不會改變元素本身,只是轉換時臨時用一下,轉換后數值用來比較。 12 ''' 13 14 list_1 = [100,20,3,40,5] 15 print(list_1) 16 list_1.sort() 17 print(list_1) 18 list_1.sort(reverse=True) 19 print(list_1) 20 21 22 23 #以上代碼執行結果如下: 24 [100, 20, 3, 40, 5] 25 [3, 5, 20, 40, 100] 26 [100, 40, 20, 5, 3]

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com list_1 = [1,3,5,7,9] print(list_1) list_2 = [1,2,3,4,5,6,7,8,9,10] print(list_2) list_3 = [[1,3,5,7,9],[2,4,6,8,10],[1,2,3],100,300,500] print(list_1 in list_2) print(list_1 in list_3) print(list_2 in list_3) for i in list_3: print(i) #以上代碼執行結果如下: [1, 3, 5, 7, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] False True False [1, 3, 5, 7, 9] [2, 4, 6, 8, 10] [1, 2, 3] 100 300 500
10>.列表復制
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com list_1 = list(range(4)) list_2 = list(range(4)) print(list_1,id(list_1)) print(list_2,id(list_2)) print(list_1 == list_2) #注意,它比較的是值並不是比較內存地址! print(list_1 is list_2) list_2[3] = 100 print(list_1) print(list_2) #以上代碼執行結果如下: [0, 1, 2, 3] 31938568 [0, 1, 2, 3] 31938632 True False [0, 1, 2, 3] [0, 1, 2, 100]

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com list_1 = [1,2,3,[100,200,300],4,5] list_2 = list_1.copy() print(list_1,id(list_1)) print(list_2,id(list_2)) print(list_2 == list_1) print(list_2 is list_1) list_2[3][1] = 666666 print(list_1,id(list_1)) print(list_2,id(list_2)) print(list_2 == list_1) print(list_2 is list_1) #以上代碼執行結果如下: [1, 2, 3, [100, 200, 300], 4, 5] 6887112 [1, 2, 3, [100, 200, 300], 4, 5] 33051592 True False [1, 2, 3, [100, 666666, 300], 4, 5] 6887112 [1, 2, 3, [100, 666666, 300], 4, 5] 33051592 True False

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com import copy list_1 = [1,2,3,[100,200,300],4,5] list_2 = copy.deepcopy(list_1) print(list_1,id(list_1)) print(list_2,id(list_2)) print( list_2 == list_1) print(list_2 is list_1) list_2[3][2] = 666 print(list_1,id(list_1)) print(list_2,id(list_2)) print( list_2 == list_1) print(list_2 is list_1) #以上代碼執行結果如下: [1, 2, 3, [100, 200, 300], 4, 5] 43582344 [1, 2, 3, [100, 200, 300], 4, 5] 43583176 True False [1, 2, 3, [100, 200, 300], 4, 5] 43582344 [1, 2, 3, [100, 200, 666], 4, 5] 43583176 False False

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com import random #返回1-5之間的整數 print(random.randint(1,5)) #從非空序列的元素中隨機挑選一個元素 print(random.choice(range(10))) #從指定范圍內,按指定基數遞增的集合中獲取一個隨機數,基數缺省值為1 print(random.randrange(1,9,2)) list_1 = [1,2,3,4,5] print(list_1) #就地打亂列表元素 random.shuffle(list_1) print(list_1) #從樣本空間或總體(序列或者集合類型)中隨機取出k個不同的元素,返回一個新的列表 print(random.sample(['a', 'b', 'c', 'd','e','f','g'], 3)) print(random.sample(['a', 'a'], 2))
11>.列表小練習

#!/usr/bin/env python #_*_conding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie #打印100內的所有素數 print(1) print(2) print(3) for i in range(3,100,2): #我們知道由於所有的偶數都能被2整除,因此我們這里可以設置步長直接跳過偶數,可以減少循環的次數! m = i ** 0.5 #我們對當前循環的數字進行開方操作 for j in range(3,i,2): #原理同上 if i % j == 0: #判斷當前參數是否能被它之前的數整除,如果不難就直接跳過循環,即把非素數過濾掉! break if j>m: #需要注意的是,這算是優化的一種方式吧,直接就過濾了一半的數據 print(i) break #以上代碼執行結果如下: 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

#!/usr/bin/env python #_*_conding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie import datetime #打印100000內的所有素數 num = 100000 count = 1 ops = 0 start = datetime.datetime.now() for i in range(3,num,2): #奇數 if i > 10 and i % 5 == 0: #直接過濾掉是5的倍數的數字,可以提高效率 ops += 1 continue for j in range(3,int(i ** 0.5)+1,2): ops += 1 if i %j == 0: #合數 break else: count += 1 #素數 delta = (datetime.datetime.now() - start).total_seconds() print(count) print(delta) print(ops) #以上代碼執行結果如下: 9592 0.187501 1338776

#!/usr/bin/env python #_*_conding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie import datetime #打印100000內的所有素數 num = 100000 ops = 0 primenums = [2] #定義一個素數列表,將素數放在這個列表中。用內存空間換計算時間,即空間換時間 start = datetime.datetime.now() for i in range(3,num,2): #奇數 flag = False #定義標志位為Flase,默認當前數字並非素數 edeg = int(i ** 0.5) ops += 1 for j in primenums: if j > edeg: flag = True #超過了開方值說明是素數,將標志位設置為True並退出本層循環 break ops += 1 if i % j == 0: #合數 break if flag: primenums.append(i) delta = (datetime.datetime.now() - start).total_seconds() print(len(primenums)) print(delta) print(ops) #以上代碼執行結果如下: 9592 0.156248 744436

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com #計算楊輝三角前6行 triangle=[[1], [1,1]] for i in range(2,6): cur = [1] pre = triangle[i-1] for j in range(len(pre)-1): cur.append(pre[j]+pre[j+1]) cur.append(1) triangle.append(cur) print(triangle)

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com #計算楊輝三角前6行 triangle=[] n = 6 for i in range(n): row = [1] triangle.append(row) if i==0: continue for j in range(i-1): row.append(triangle[i-1][ j]+triangle[i-1][ j+1]) row.append(1) print(triangle)

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com #計算楊輝三角前6行 n = 6 newline = [1] # 相當於計算好的第一行 print(newline) for i in range(1, n): oldline = newline.copy() # 淺拷貝並補0 oldline.append(0) # 尾部補0相當於兩端補0 newline.clear() # 使用append,所以要清除 offset = 0 while offset <= i: newline.append(oldline[offset-1] + oldline[offset]) offset += 1 print(newline)

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com #計算楊輝三角前6行 n = 6 newline = [1] # 相當於計算好的第一行 print(newline) for i in range(1, n): oldline = newline.copy() # 淺拷貝並補0 oldline.append(0) # 尾部補0相當於兩端補0 newline.clear() # 使用append,所以要清除 for j in range(i+1): newline.append(oldline[ j - 1] + oldline[j]) print(newline)

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com #計算楊輝三角前6行 triangle = [] n = 6 for i in range(n): row = [1] # 開始的1 for k in range(i): # 中間填0,尾部填1 row.append(1) if k == i-1 else row.append(0) triangle.append(row) if i == 0: continue for j in range(1,i//2+1): # i=2第三行才能進來 val = triangle[i - 1][ j-1] + triangle[i - 1][ j] row[j] = val if i != 2*j: # 奇數個數的中點跳過 row[-j-1] = val print(triangle)

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com #計算楊輝三角前6行 triangle = [] n = 6 for i in range(n): row = [1] * (i+1) # 一次性開辟 triangle.append(row) for j in range(1,i//2+1): # i=2第三行才能進來 val = triangle[i - 1][ j-1] + triangle[i - 1][ j] row[j] = val if i != 2*j: # 奇數個數的中點跳過 row[-j-1] = val print(triangle)
四.元組(tuple)
1>.元組(tuple)概述
一個有序的元素組成的集合
使用小括號( ) 表示
元組是不可變對象
2>.元組的定義和初始化
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com #定義元組的幾種常見姿勢如下所示 t1 = tuple() # 工廠方法 t2 = () t3 = tuple(range(1,9,2)) # iteratable t4 = (2,4,6,3,4,2) t5 = (1,) # 一個元素元組的定義,注意有個逗號 t6 = (1,)*5 t7 = (1,2,3) * 6 print(t1) print(t2) print(t3) print(t4) print(t5) print(t6) print(t7)

() () (1, 3, 5, 7) (2, 4, 6, 3, 4, 2) (1,) (1, 1, 1, 1, 1) (1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
3>.元組元素的訪問
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' 支持索引(下標) 正索引:從左至右,從0開始,為列表中每一個元素編號 負索引:從右至左,從-1開始 正負索引不可以超界,否則引發異常IndexError 元組通過索引訪問 tuple[index] ,index就是索引,使用中括號訪問 ''' name_list = ("Jason Yin","Jennny","Danny","Liming","Dog Cutting",[10,20,30]) print(name_list) print(name_list,type(name_list)) print(name_list[0]) print(name_list[-2]) name_list[-1][1] = 666 print(name_list)

('Jason Yin', 'Jennny', 'Danny', 'Liming', 'Dog Cutting', [10, 20, 30]) ('Jason Yin', 'Jennny', 'Danny', 'Liming', 'Dog Cutting', [10, 20, 30]) <class 'tuple'> Jason Yin Dog Cutting ('Jason Yin', 'Jennny', 'Danny', 'Liming', 'Dog Cutting', [10, 666, 30])
4>.元組的查詢操作(元組是只讀的,所以增,改,刪方法都沒有!)

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' index(value,[start,[stop]]) 通過值value,從指定區間查找列表內的元素是否匹配 匹配第一個就立即返回索引 匹配不到,拋出異常ValueError ''' name_list = ("Jason Yin","Jennny","Danny","Liming","Dog Cutting") print(name_list.index("Jennny")) print(name_list.index("Jason Yin")) #以上代碼輸出結果如下: 1 0

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' count(value) 返回列表中匹配value的次數 ''' t1 = (1,3,2,3,4,3,2,3,5,3,2,3,6,3) print(t1.count(3)) print(t1.count(2)) #以上代碼輸出結果如下: 7 3

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' len(tuple) 返回元素的個數 ''' t1 = (1,3,2,3,4,3,2,3,5,3,2,3,6,3) print(len(t1)) #以上代碼輸出結果如下: 14
5>. 命名元組namedtuple使用案例
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com from collections import namedtuple Point = namedtuple('_Point',['x','y']) # Point為返回的類,后面的'x','y'表示定義的屬性名稱 p = Point(100, 200) print(p.x) print(p.y) Student = namedtuple('Student', 'Name Age') #Student為返回的類名,這是咱們自定義的,我們可以直接使用該類名,調用我們自定給定的屬性名稱 tom = Student('tom', 20) jerry = Student('jerry', 18) print(tom.Name) print(tom.Age) print(jerry.Name) print(jerry.Age) #以上代碼執行結果如下: 100 200 tom 20 jerry 18

1 #!/usr/bin/env python 2 #_*_conding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie 5 6 from collections import namedtuple 7 8 student = namedtuple("Student",'name,age,address') #注意,student為標識符,可以通過閱讀源碼,傳入參方式會被轉換成list 9 10 jason = student("尹正傑",18,"北京") 11 12 print(jason.address) 13 print(jason.age) 14 print(jason.name) 15 print(jason) 16 17 18 19 20 #以上代碼執行結構如下: 21 北京 22 18 23 尹正傑 24 Student(name='尹正傑', age=18, address='北京')
6>.元組練習 (依次接收用戶輸入的3個數,排序后打印)

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com nums = [] for i in range(1,4): nums.append(int(input("請輸入第{}個整數:>>> ".format(i)))) if nums[0] > nums[1]: if nums[0] > nums[2]: i3 = nums[0] if nums[1] > nums[2]: i2 = nums[1] i1 = nums[2] else: i2 = nums[2] i1 = nums[1] else: i3 = nums[2] i2 = nums[0] i1 = nums[1] else:#0<1 if nums[0] > nums[2]: i3 = nums[1] i2 = nums[0] i1 = nums[2] else:#0<2 if nums[1] < nums[2]: i3 = nums[2] i2 = nums[1] i1 = nums[0] else: i3 = nums[1] i2 = nums[2] i1 = nums[0] print(i1,i2,i3)

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com nums = [] out = None for i in range(1,4): nums.append(int(input("請輸入第{}個整數:>>> ".format(i)))) if nums[0] > nums[1]: if nums[0] > nums[2]: if nums[1] > nums[2]: out = [2,1,0] else: out = [1,2,0] else: out = [1,2,0] else: if nums[0] > nums[2]: out = [2,0,1] else:#0<2 if nums[1] < nums[2]: out = [0,1,2] else: out = [0,2,1] out.reverse() for i in out: print(nums[i],end=",")

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com nums = [] for i in range(1,4): nums.append(int(input("請輸入第{}個整數:>>> ".format(i)))) #此處不能使用for循環,不能一般迭代該列表,同時刪除或者增加該列表 while True: cur = min(nums) print(cur) nums.remove(cur) if len(nums) == 1: print(nums[0]) break

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com nums = [] for i in range(1,4): nums.append(int(input("請輸入第{}個整數:>>> ".format(i)))) nums.sort() print(nums)

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com numlist = [ [1,9,8,5,6,7,4,3,2], ] nums = numlist[0] print(nums) length = len(nums) count_swap = 0 count = 0 for i in range(length): for j in range(length - i - 1): count += 1 if nums[j] > nums[ j + 1]: tmp = nums[j] nums[j] = nums[j+1] nums[j+1] = tmp count_swap += 1 print(nums,count_swap,count)

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com numlist = [ [1,9,8,5,6,7,4,3,2], [1,2,3,4,5,6,7,8,9], [1,2,3,4,5,6,7,8,9] ] nums = numlist[2] print(nums) length = len(nums) count_swap = 0 count = 0 for i in range(length): flag = False for j in range(length - i -1): count += 1 if nums[j] > nums[j+1]: tmp = nums[j] nums[j] =nums[j+1] nums[j+1] = tmp flag = True count_swap += 1 if not flag: break print(nums,count_swap,count)
五.字符串
1>.字符串概述
一個個字符組成的有序的序列,是字符的集合
使用單引號、雙引號、三引號引住的字符序列
字符串是不可變對象
Python3起,字符串就是Unicode類型
2>.字符串定義初始化
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com s1 = 'string' s2 = "string2" s3 = '''this's a "String" ''' s4 = 'hello \n http://www.cnblogs.com/yinzhengjie' s5 = r"hello \n http://www.cnblogs.com/yinzhengjie" s6 = 'c:\windows\nt' s7 = R"c:\windows\nt" s8 = 'c:\windows\\nt' sql = """select * from user where name='tom' """ print(s1) print(s2) print(s3) print(s4) print(s5) print(s6) print(s7) print(s8) print(sql)

string string2 this's a "String" hello http://www.cnblogs.com/yinzhengjie hello \n http://www.cnblogs.com/yinzhengjie c:\windows t c:\windows\nt c:\windows\nt select * from user where name='tom'
3>.字符串元素訪問

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com sql = "select * from user where name='tom'" print(sql[5]) print(sql[1:5]) print(sql[-1])

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com sql = "select * from user where name='tom'" for item in sql: print(item) print(type(item))

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com sql = "select * from user where name='tom'" list_1 = list(sql) print(list_1) print(len(list_1)) print(sql[0]) print(list_1[0]) print(sql[0] == list_1[0])
4>.字符串join連接

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' "string".join(iterable) -> str 將可迭代對象連接起來,使用string作為分隔符 可迭代對象本身元素都是字符串 返回一個新字符串 ''' list_1 = ['1','2','3'] print("\"".join(list_1)) # 分隔符是雙引號 print(" ".join(list_1)) print("\n".join(list_1))

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com a = "I love you !" b = "Me too." c = a + b print(c)
5>. 字符串分割

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' split系 將字符串按照分隔符分割成若干字符串,並返回列表 split(sep=None, maxsplit=-1) -> list of strings 從左至右 sep 指定分割字符串,缺省的情況下空白字符串作為分隔符 maxsplit 指定分割的次數,-1 表示遍歷整個字符串 ''' s1 = "I'm \ta super student." print(s1) print(s1.split()) print(s1.split('s')) print(s1.split('super')) print(s1.split('super ')) print(s1.split(' ')) print(s1.split(' ',maxsplit=2)) print(s1.split('\t',maxsplit=2)) print(s1)

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' rsplit(sep=None, maxsplit=-1) -> list of strings 從右向左 sep 指定分割字符串,缺省的情況下空白字符串作為分隔符 maxsplit 指定分割的次數,-1 表示遍歷整個字符串 ''' s1 = "I'm \ta super student." print(s1) print(s1.rsplit()) print(s1.rsplit('s')) print(s1.rsplit('super')) print(s1.rsplit('super ')) print(s1.rsplit(' ')) print(s1.rsplit(' ',maxsplit=2)) print(s1.rsplit('\t',maxsplit=2))

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' splitlines([keepends]) -> list of strings 按照行來切分字符串 keepends 指的是是否保留行分隔符 行分隔符包括\n、\r\n、\r等 ''' print('ab c\n\nde fg\rkl\r\n'.splitlines()) print('ab c\n\nde fg\rkl\r\n'.splitlines(True)) s1 = '''I'm a super student. You're a super teacher.''' print(s1) print(s1.splitlines()) print(s1.splitlines(True))

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' partition(sep) -> (head, sep, tail) 從左至右,遇到分隔符就把字符串分割成兩部分,返回頭、分隔符、尾三部分的三元組;如果沒有找到分隔符,就返回頭、2個空元素的三元組 sep 分割字符串,必須指定 ''' s1 = "I'm a super student." print(s1.partition('s')) print(s1.partition('stu')) # print(s1.partition('')) print(s1.partition('abc'))
6>.字符串大小寫

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com s1 = "I'm a super man" print(s1) print(s1.upper()) #以上代碼執行結果如下: I'm a super man I'M A SUPER MAN

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com s1 = "I'm a super man" print(s1) print(s1.lower()) #以上代碼執行結果如下: I'm a super man i'm a super man

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com s1 = "I'm a super man" print(s1) print(s1.swapcase()) #以上代碼執行結果如下: I'm a super man i'M A SUPER MAN
7>.字符串排版

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com s1 = "I'm a super man" print(s1) print(s1.title()) #以上代碼執行結果如下: I'm a super man I'M A Super Man

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com s1 = "i'm a super man" print(s1) print(s1.capitalize()) #以上代碼執行結果如下: i'm a super man I'm a super man

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' center(width[, fillchar]) -> str width 打印寬度 fillchar 填充的字符 ''' s1 = "*"*10 print(s1) print(s1.center(50)) print(s1.center(50,'#')) #以上代碼執行結果如下: ********** ********** ####################**********###################

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' zfill(width) -> str width 打印寬度,居右,左邊用0填充 ''' s1 = "*"*10 print(s1) print(s1.zfill(50)) #以上代碼執行結果如下: ********** 0000000000000000000000000000000000000000**********

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' ljust(width[, fillchar]) -> str 左對齊 ''' s1 = "*"*10 print(s1) print(s1.ljust(50,"#")) #以上代碼執行結果如下: ********** **********########################################

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' rjust(width[, fillchar]) -> str 右對齊 ''' s1 = "*"*10 print(s1) print(s1.rjust(50,"#")) #以上代碼執行結果如下: ********** ########################################**********
8>.字符串修改(注意,字符串本身是不可變的,要明白這里的修改其本質是字符串中找到匹配替換為新子串,返回新字符串)

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ replace(old, new[, count]) -> str 字符串中找到匹配替換為新子串,返回新字符串 count表示替換幾次,不指定就是全部替換 """ s1 = "www.yinzhengjie.org.cn" print(s1) print(s1.replace('w','p')) print(s1.replace('w','p',2)) print(s1.replace('w','p',3)) print(s1.replace('ww','p')) print(s1.replace('ww','p',2)) print(s1.replace('www','python',2)) #以上代碼執行結果如下: www.yinzhengjie.org.cn ppp.yinzhengjie.org.cn ppw.yinzhengjie.org.cn ppp.yinzhengjie.org.cn pw.yinzhengjie.org.cn pw.yinzhengjie.org.cn python.yinzhengjie.org.cn

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ strip([chars]) -> str 從字符串兩端去除指定的字符集chars中的所有字符 如果chars沒有指定,去除兩端的空白字符 """ s1 = "\r \n \t Hello Python \n \t" s2 = " I am very very very sorry " print(s1) print(s1.strip()) print(s2) print(s2.strip("r")) print(s2.strip("r ")) print(s2.strip("r y")) print(s2.strip("r yIamso"))

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ rstrip([chars]) -> str 從字符串右邊開始去除指定的字符集chars中的所有字符 """ s1 = " I am very very very sorry " print(s1) print(s1.rstrip("r yIamso")) #以上代碼執行結果如下: I am very very very sorry I am very very ve

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ lstrip([chars]) -> str 從字符串左邊開始去除指定的字符集chars中的所有字符 """ s1 = " I am very very very sorry " print(s1) print(s1.lstrip("r yIamso")) print(s1.rstrip("r yIamso")) #以上代碼執行結果如下: I am very very very sorry very very very sorry I am very very ve
9>.字符串查找
時間復雜度:
find,index,count方法都是O(n)。
隨着列表的數據規模的增大,而效率下降。
len(string):
返回字符串的長度,即字符的個數。

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ find(sub[, start[, end]]) -> int 在指定的區間[start, end),從左至右,查找子串sub。找到返回索引,沒找到返回-1 """ s1 = "I am very very very sorry" print(s1) print(s1.find("very")) print(s1.find("very",5)) print(s1.find("very",6,13)) #以上代碼執行結果如下: I am very very very sorry 5 5 -1

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ rfind(sub[, start[, end]]) -> int 在指定的區間[start, end),從右至左,查找子串sub。找到返回索引,沒找到返回-1 """ s1 = "I am very very very sorry" print(s1) print(s1.rfind("very")) print(s1.rfind("very",10,15)) print(s1.rfind("very",-10,-1)) #以上代碼執行結果如下: I am very very very sorry 15 10 15

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ index(sub[, start[, end]]) -> int 在指定的區間[start, end),從左至右,查找子串sub。找到返回索引,沒找到拋出異常ValueError """ s1 = "I am very very very sorry" print(s1) print(s1.index("very")) print(s1.index("very",5)) print(s1.index('very',6,20)) #以上代碼執行結果如下: I am very very very sorry 5 5 10

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ rindex(sub[, start[, end]]) -> int 在指定的區間[start, end),從左至右,查找子串sub。找到返回索引,沒找到拋出異常ValueError """ s1 = "I am very very very sorry" print(s1) print(s1.rindex('very',10)) print(s1.rindex('very',10,15)) print(s1.rindex('very',-10,-1)) #以上代碼執行結果如下: I am very very very sorry 15 10 15

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ len(string) 返回字符串的長度,即字符的個數 """ s1 = "I am very very very sorry" print(s1) print(len(s1)) #以上代碼執行結果如下: I am very very very sorry 25

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ 時間復雜度 index和count方法都是O(n) 隨着列表數據規模的增大,而效率下降 count(sub[, start[, end]]) -> int 在指定的區間[start, end),從左至右,統計子串sub出現的次數 """ s1 = "I am very very very sorry" print(s1) print(s1.count('very',5)) print(s1.count('very',10,14)) #以上代碼執行結果如下: I am very very very sorry 3 1
10>.字符串判斷

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ startswith(prefix[, start[, end]]) -> bool 在指定的區間[start, end),字符串是否是prefix開頭 """ s1 = "I am very very very sorry" print(s1) print(s1.startswith('very')) print(s1.startswith('very',5)) print(s1.startswith('very',5,9)) #以上代碼執行結果如下: I am very very very sorry False True True

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ endswith(suffix[, start[, end]]) -> bool 在指定的區間[start, end),字符串是否是suffix結尾 """ s1 = "I am very very very sorry" print(s1) print(s1.endswith('very',5,9)) print(s1.endswith('sorry',5)) print(s1.endswith('sorry',5,-1)) print(s1.endswith('sorry',5,100)) #以上代碼執行結果如下: I am very very very sorry True True False True

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ isalnum() -> bool 是否是字母和數字組成 """ s1 = "I am very very very sorry" s2 = 'ABC123' print(s1) print(s1.isalnum()) print(s2) print(s2.isalnum()) #以上代碼執行結果如下: I am very very very sorry False ABC123 True

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ isalpha() 是否是字母 """ s1 = "I am very very very sorry" s2 = 'ABCDE' print(s1) print(s1.isalpha()) print(s2) print(s2.isalpha()) #以上代碼執行結果如下: I am very very very sorry False ABCDE True

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ isdecimal() 是否只包含十進制數字 """ s1 = '10EF' s2 = '123456' print(s1.isdecimal()) print(s2.isdecimal()) #以上代碼執行結果如下: False True

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ isdigit() 是否全部數字(0~9) """ s1 = '10EF' s2 = '123456' print(s1.isdigit()) print(s2.isdigit()) #以上代碼執行結果如下: False True

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ isidentifier() 是不是字母和下划線開頭,其他都是字母、數字、下划線 """ s1 = '10EF' s2 = '_123456' s3 = '_len' s4 = 'Abc_123' s5 = 'Abc#123' print(s1.isidentifier()) print(s2.isidentifier()) print(s3.isidentifier()) print(s4.isidentifier()) print(s5.isidentifier()) #以上代碼執行結果如下: False True True True False

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ islower() 是否都是小寫 """ s1 = 'Abc' s2 = 'abc' print(s1.islower()) print(s2.islower()) #以上代碼執行結果如下: False True

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ isupper() 是否全部大寫 """ s1 = 'Abc' s2 = 'ABC' print(s1.isupper()) print(s2.isupper()) #以上代碼執行結果如下: False True

11>.字符串格式化

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ 字符串的格式化是一種拼接字符串輸出樣式的手段,更靈活方便 join拼接只能使用分隔符,且要求被拼接的是可迭代對象 + 拼接字符串還算方便,但是非字符串需要先轉換為字符串才能拼接 在2.5版本之前,只能使用printf style風格的print輸出 printf-style formatting,來自於C語言的printf函數 格式要求 占位符:使用%和格式字符組成,例如%s、%d等 s調用str(),r會調用repr()。所有對象都可以被這兩個轉換。 占位符中還可以插入修飾字符,例如%03d表示打印3個位置,不夠前面補零 format % values,格式字符串和被格式的值之間使用%分隔 values只能是一個對象,或是一個和格式字符串占位符數目相等的元組,或一個字典 """ print("I am %05d" % (18,)) print('I like %s.' % 'Python') print('%3.2f%% , 0x%x, 0X%02X' % (89.7654, 10, 15)) print("I am %-5d" % (20,)) #以上代碼執行結果如下: I am 00018 I like Python. 89.77% , 0xa, 0X0F I am 20

1 #!/usr/bin/env python 2 #_*_conding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie 5 6 7 """ 8 format函數格式字符串語法——Python鼓勵使用 9 "{} {xxx}".format(*args, **kwargs) -> str 10 args是位置參數,是一個元組 11 kwargs是關鍵字參數,是一個字典 12 花括號表示占位符 13 {}表示按照順序匹配位置參數,{n}表示取位置參數索引為n的值 14 {xxx}表示在關鍵字參數中搜索名稱一致的 15 {{}} 表示打印花括號 16 """ 17 18 #位置參數,,這就是按照位置順序用位置參數替換前面的格式字符串的占位符中 19 print("{}:{}".format('192.168.1.100',8888)) 20 21 #關鍵字參數或命名參數,,位置參數按照序號匹配,關鍵字參數按照名詞匹配 22 print("{server} {1}:{0}".format(8888, '192.168.1.100', server='Web Server Info : ')) 23 24 #訪問元素 25 "{0[0]}.{0[1]}".format(('magedu','com')) 26 27 #對象屬性訪問 28 from collections import namedtuple 29 Point = namedtuple('Point','x y') 30 p = Point(4,5) 31 print("{{{0.x},{0.y}}}".format(p)) 32 33 #對齊 34 print('{0}*{1}={2:<2}'.format(3,2,2*3)) 35 print('{0}*{1}={2:<02}'.format(3,2,2*3)) 36 print('{0}*{1}={2:>02}'.format(3,2,2*3)) 37 print('{:^30}'.format('centered')) 38 print('{:*^30}'.format('centered')) 39 40 #進制 41 print("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)) 42 print("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)) 43 octets = [192, 168, 0, 1] 44 print('{:02X}{:02X}{:02X}{:02X}'.format(*octets)) 45 46 47 #浮點數 48 print("{}".format(3**0.5)) 49 print("{:f}".format(3**0.5)) #精確度默認6 50 print("{:10f}".format(3**0.5)) #右對齊,寬度10 51 print("{:2}".format(102.123)) #寬度為2的數字 52 print("{:.2}".format(3**0.5)) #2個有效數字 53 print("{:.2f}".format(3**0.5)) #保留小數點后2位 54 print("{:3.2f}".format(3**0.5)) #寬度為3,保留小數點后2位 55 print("{:20.3f}".format(0.2745)) #寬度為20,保留小數點后3位,四舍五入 56 print("{:3.3%}".format(1/3)) #寬度位3,保留3位小數,注意寬度可以被撐破,我們發現寬度為3並沒有生效,因為光小數點后面保留3為就已經打破了寬度為3的限定,說明寬度限定只是一個軟限定,而且數字使用%來顯示的喲~ 57 58 59 60 61 #以上代碼輸出結果如下: 62 192.168.1.100:8888 63 Web Server Info : 192.168.1.100:8888 64 {4,5} 65 3*2=6 66 3*2=60 67 3*2=06 68 centered 69 ***********centered*********** 70 int: 42; hex: 2a; oct: 52; bin: 101010 71 int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010 72 C0A80001 73 1.7320508075688772 74 1.732051 75 1.732051 76 102.123 77 1.7 78 1.73 79 1.73 80 0.275 81 33.333%
12>.字符串練習
用戶輸入一個數字:
判斷是幾位數
打印每一位數字及其重復的次數。打印順序個,十,百,千,萬...位打印
輸入5個數字,打印每個數字的位數,將三個數字排序打印,要求升序打印。

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com num = " " while True: num = input("請輸入一個整數:>>>").strip().lstrip("0") if num.isdigit(): break else: print("輸入錯誤,請輸入一個[0-9]的整數.") count = [0] * 10 for i in range(10): count[i] = num.count(str(i)) for j in range(10): if count[j] : print("數字 {} 出現了 {} 次".format(j,count[j])) list_1 = list(num) list_1.reverse() print(list_1)
六.bytes和bytearray
1>.bytes概述
Python3引入兩個新類型 bytes 不可變字節序列 bytearray 字節數組 可變 字符串與bytes 字符串是字符組成的有序序列,字符可以使用編碼來理解 bytes是字節組成的有序的不可變序列 bytearray是字節組成的有序的可變序列 編碼與解碼 字符串按照不同的字符集編碼encode返回字節序列bytes encode(encoding='utf-8', errors='strict') -> bytes 字節序列按照不同的字符集解碼decode返回字符串 bytes.decode(encoding="utf-8", errors="strict") -> str bytearray.decode(encoding="utf-8", errors="strict") -> str ASCII(American StandardCode for InformationInterchange,美國信息交換標准代碼)是基於拉丁字母的一套單字節編碼系統.
熟記以下結果ASCII對應的字符:
\t,
\r,
\n,
0-9,
A-Z,
a-z,
2>.bytes定義
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' 定義 bytes() 空bytes bytes(int) 指定字節的bytes,被0填充 bytes(iterable_of_ints) -> bytes [0,255]的int組成的可迭代對象 bytes(string, encoding[, errors]) -> bytes 等價於string.encode() bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer 從一個字節序列或者buffer復制出一個新的不可變的bytes對象 使用b前綴定義: 案例一:只允許基本ASCII使用字符形式b'abc9' 案例二:使用16進制表示b"\x41\x61" ''' #空bytes b1 = bytes() #指定字節的bytes,被0填充 b2 = bytes(3) #bytes [0,255]的int組成的可迭代對象 b3 = bytes([1,3,5,7,9]) #bytes 等價於string.encode() b4 = bytes("ABC","utf8") b5 = "ABC".encode() b6 = b4.decode() b7 = b5.decode() #從一個字節序列或者buffer復制出一個新的不可變的bytes對象 a = b'abc' b = bytes(a) print(b1) print(b2) print(b3) print(b4) print(b5) print(b6) print(b7) print(a) print(b) print(id(a) == id(b)) print(id(a) is id(b)) #以上代碼執行結果如下: b'' b'\x00\x00\x00' b'\x01\x03\x05\x07\t' b'ABC' b'ABC' ABC ABC b'abc' b'abc' True False
3>.bytes操作

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ 和str類型類似,都是不可變類型,所以方法很多都一樣。只不過bytes的方法,輸入是bytes,輸出是bytes """ print(b'abcdef'.replace(b'f',b'k')) print(b'abc'.find(b'b')) #以上代碼執行結果如下: b'abcdek' 1


#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ hex() 返回16進制表示的字符串 """ print('abc'.encode().hex()) #以上代碼執行結果如下: 616263

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com """ 索引 b'abcdef'[2] 返回該字節對應的數,int類型 """ print(b'abcdef'[2] ) #以上代碼執行結果如下: 99
4>.bytearray定義
bytearray() 空bytearray bytearray(int) 指定字節的bytearray,被0填充 bytearray(iterable_of_ints) -> bytearray [0,255]的int組成的可迭代對象 bytearray(string, encoding[, errors]) -> bytearray 近似string.encode(),不過返回可變對象 bytearray(bytes_or_buffer) 從一個字節序列或者buffer復制出一個新的可變的bytearray對象
注意,b前綴定義的類型是bytes類型
5>.bytearray操作

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com b = bytearray() print(b) #append(int) 尾部追加一個元素 b.append(97) b.append(99) print(b) #insert(index, int) 在指定索引位置插入元素 b.insert(1,98) print(b) #extend(iterable_of_ints) 將一個可迭代的整數集合追加到當前bytearray b.extend([65,66,67]) print(b) #pop(index=-1) 從指定索引上移除元素,默認從尾部移除 b.remove(66) print(b) #remove(value) 找到第一個value移除,找不到拋ValueError異常 b.pop() print(b) #reverse() 翻轉bytearray,就地修改 b.reverse() print(b) #clear() 清空bytearray b.clear() print(b) #以上代碼執行結果如下: bytearray(b'') bytearray(b'ac') bytearray(b'abc') bytearray(b'abcABC') bytearray(b'abcAC') bytearray(b'abcA') bytearray(b'Acba') bytearray(b'')
6>.字節序
小白一開始聽到字節序這個名詞,估計會有點蒙蔽,其實顧名思義就是字節的順序嘛。計算機硬件有兩種儲存數據的方式:大端字節序(big endian)和小端字節序(little endian)。 ok,我們先不解釋大端模式和小端模式,我先問你一個問題,"我喜歡你"這4個字大家都知道啥意思吧?在古代的時候他們會這樣寫:"你歡喜我"。這就是我們寫字的順序。其實在現代也有很多復古的酒店,參觀還保持這種風格。說白了就是讀取的順序不同。 舉例來說,數值0x2211使用兩個字節儲存:高位字節是0x22,低位字節是0x11。 大端字節序:高位字節在前,低位字節在后,這是人類讀寫數值的方法。 小端字節序:低位字節在前,高位字節在后,即以0x1122形式儲存。 關於字節序模式的使用,在各個平台可能不太一樣,如下所示: Intel x86 CPU使用小端模式 網絡傳輸更多使用大端模式 Windows,Linux使用小端模式 Mac OS使用大端模式 Java虛擬機是大端模式
7>.int和bytes
#!/usr/bin/env python #_*_conding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie #將一個字節數組表示成整數 i = int.from_bytes(b"abc","big") print(i,hex(i)) #將一個整數表達成一個指定長度的字節數組 print(i.to_bytes(3,"big")) b = bytearray() b.append(97) b.extend(range(98,100)) print(b) #以上代碼執行結果如下: 6382179 0x616263 b'abc' bytearray(b'abc')
七.切片
1>.線性結構
線性結構 可迭代for ... in len()可以獲取長度 通過下標可以訪問 可以切片
學過的線性結構 列表、元組、字符串、bytes、bytearray
2>.切片概要
切片
通過索引區間訪問線性結構的一段數據
sequence[start:stop] 表示返回[start, stop)區間的子序列
支持負索引
start為0,可以省略
stop為末尾,可以省略
超過上界(右邊界),就取到末尾;超過下界(左邊界),取到開頭
start一定要在stop的左邊
[:] 表示從頭至尾,全部元素被取出,等效於copy()方法
3>.切片舉例
#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com s = "www.yinzhengjie.org.cn" print(s[4:10]) print(s[:10]) print(s[4:]) print(s[:]) print(s[:-1]) print(s[4:-4]) print(s[4:-50]) print(s[-40:10]) print(bytearray(b'www.yinzhengjie.org.cn')[-4:10]) print(tuple("www.yinzhengjie.org.cn")[-10:10]) print(list("www.yinzhengjie.org.cn")[-10:-4]) #以上代碼執行結果如下: yinzhe www.yinzhe yinzhengjie.org.cn www.yinzhengjie.org.cn www.yinzhengjie.org.c yinzhengjie.or www.yinzhe bytearray(b'') () ['j', 'i', 'e', '.', 'o', 'r']

#!/usr/bin/env python #_*_coding:utf-8_*_ #@author :yinzhengjie #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ #EMAIL:y1053419035@qq.com ''' 步長切片 [start:stop:step] step為步長,可以正、負整數,默認是1 step要和start:stop同向,否則返回空序列 ''' print("www.yinzhengjie.org.cn"[4:10:2]) print(list("www.yinzhengjie.org.cn"[4:10:-2])) print(tuple("www.yinzhengjie.org.cn")[-10:-4:2]) print(b"www.yinzhengjie.org.cn"[-4:-10:2]) print(bytearray(b"www.yinzhengjie.org.cn")[-4:-10:-2]) #以上代碼執行結果如下: ynh [] ('j', 'e', 'o') b'' bytearray(b'goe')