Python基礎(中)
前言
print("_ooOoo_") print("o8888888o") print("88.88") print("(| -_- |)") print("O\\ = /O") print("____/`---'\\____") print(".' \\| |// `.") print("/ \\||| : |||// \\") print("/ _||||| -:- |||||- \\") print("| | \\\\\\ - /// | |") print("| \\_| ''\\---/'' | |") print("\\ .-\\__ `-` ___/-. /") print("___`. .' /--.--\\ `. . __") print("."" '< `.___\\_<|>_/___.' >'"".") print("| | : `- \\`.;`\\ _ /`;.`/ - ` : | |") print("\\ \\ `-. \\_ __\\ /__ _/ .-` / /") print("======`-.____`-.___\\_____/___.-`____.-'====== ") print("`=---='") print("") print(".............................................") print("佛祖鎮樓國慶快樂")
字串基礎(String)
python中字元的定義使用 單引號 或者 雙引號 都可以,例如:
str1="Hello" #或者 str2="Jonins"
注意: 在python3中input獲取鍵盤輸入的資料,都以字串的方式進行儲存,即使輸入的是數字。
下標&切片
1.下標
下標:可以理解為陣列類資料型別內元素的 索引 。列表與元組支援下標索引,字串是字元的陣列,所以也支援下標索引。索引從0開始,而記憶體中實際儲存如下:
2.切片
切片:是 指對操作的物件擷取其中一部分的操 作。字串、列表、元組都支援切片操作。切片的語法格式如下:
1 變數名[起始:結束:步長]
注意:選取的區間屬於 左閉右開型 ,既從起始位開始,到結束位的前一位,不包含結束位本身。說明示例如下:
1 name='0123456789' 2 print(name[0:3])#取下標0-2的字元 3 print(name[3:5])#取下標3-4的字元 4 print(name[3:])#取下標3開始到最後的字元 5 print(name[3:-3])#取下標3開始到倒數第3個之間的字元(不包含倒數第三) 6 print(name[3:-1:2])#取標3開始到倒數第一個之間間隔為2-1的字元(步長,預設是1,當指定的時取值是步長的值,可以理解為中間間隔(步長-1)) 7 print(name[-1::-1])#倒敘輸出字串
列表基礎(List)
1.列表基礎
列表型別的格式:
1 testList=[xxx,yyy,zzz....nnn]
列表支援切片和下標操作,而 python 比 C語言 的陣列強大的地方在於 列表中的元素可以是不同型別 的:
1 tuple=['jonins01',2,'jonins02',3.3] 2 print(tuple[2]) 3 tuple2=tuple[0:2] 4 print(tuple2)
2.列表的遍歷
為了更有效的輸出列表的每個資料,可以使用迴圈來完成,列表的遍歷可以使用 for 迴圈或者 while 迴圈來實現,示例如下:
1 nameList=['jonins1','jonins2','jonins'] 2 print('-----for迴圈遍歷-----') 3 for name in nameList: 4print(name) 5 print('-----while迴圈遍歷-----') 6 i=0 7 while i<len(nameList): 8print(nameList[i]) 9i+=1
元組基礎(Tuple)
1.元組基礎
python的元組與列表類似,不同之處在於元組的 元素不能修改 。 元組使用小括號,列表使用方括號 。列表的格式如下:
1 tuple=(xxx,yyy,zzz....nnn)
python中不允許修改元組的資料,包括不能刪除其中的元素。 元組同樣支援切片和下標操作 。
1 tuple=('jonins1',2,'jonins',3.3) 2 print(tuple[2]) 3 tuple2=tuple[0:] 4 print(tuple2)
2.元組的遍歷
元組同樣可以遍歷,通過 for 迴圈和 while 迴圈都可以實現:
1 tuple=('jonins1',2,'jonins',3.3) 2 print('-----for迴圈遍歷-----') 3 for t in tuple: 4print(t) 5 print('-----while迴圈遍歷-----') 6 i=0 7 while i<len(tuple): 8print(tuple[i]) 9i+=1
字典基礎(Dictionary)
1.字典基礎
說明:字典是key/value鍵值對集合。字典和列表一樣,都可以儲存多個數據。列表中找某個元素是根據下標進行,而字典中找某個元素是根據key查詢。字典的格式如下:
1 info={'key1':value1,'key2':value2,......'keyn':valuen}
示例:
1 info={'name':'jonins','age':18,'sex':'man'} 2 print(info['age'])
注意:
1.字典的鍵(key)可以是任何不可變型別。但不可重複。
2.字典的值(value)可以是任何型別。
3.若訪問不存在的鍵(key)則會報錯。
2.字典的遍歷
字典提供內建的方法 keys() 、 values() 、 items() 方法,可以根據需求做所需要的遍歷操作,示例如下:
1 info={'name':'jonins',3:18,'sex':'man'} 2 print('遍歷字典的鍵(key)') 3 for key in info.keys(): 4print(key) 5 print('遍歷字典的值(value)') 6 for value in info.values(): 7print(value) 8 print('遍歷字典的項(元素)') 9 for item in info.items(): 10print(item)
字串常用操作(String)
1.find&rfind
find() 方法檢測字串中是否包含子字串 str ,如果指定 start(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍內,如果指定範圍內如果包含指定索引值,返回的是索引值在字串中的起始位置。如果不包含索引值,返回-1。
rfind() 方法類似於 find() 方法,不過是從右邊開始查詢。
語法格式:
1 myStr.find(str,start,end)
說明:
myStr:指定檢索的字串。
str:檢測的字串或字元。
start:開始索引,預設為0。
end: 結束索引,預設為字串的長度。
示例如下:
1 stringInfo = 'hello my name is jonins' 2 result = stringInfo.find('my', 0, len(stringInfo)) 3 print(result)
2.index&rindex
跟 find() 方法一樣, index() 如果在檢測字元或字串不存在會報一個異常。
rindex() 方法類似於 index() ,不過是從右邊開始。
3.count
count() 方法用於統計字串裡某個字元出現的次數。可選引數為在字串搜尋的開始與結束位置。
語法格式:
1 myStr.count(str,start,end)
說明:
myStr:指定檢索的字串。
str:搜尋的子字串
start:字串開始搜尋的位置。預設為第一個字元,第一個字元索引值為0。
end:字串中結束搜尋的位置。字元中第一個字元的索引為 0。預設為字串的最後一個位置。
示例如下:
1 stringInfo = 'hello my name is jonins' 2 result = stringInfo.count('m', 0, -1) 3 print(result)
4.replace
eplace() 方法把字串中的 old(舊字串) 替換成 new(新字串),如果指定第三個引數max,則替換不超過 max 次。
語法格式:
1 myStr.replace(old, new[, max])
說明:
myStr:指定替換的字串。
old:將被替換的子字串。
new:新字串,用於替換old子字串。
max :可選字串, 替換不超過 max 次
示例如下:
1 stringInfo = 'jonins jonins jonins jonins ' 2 stringInfo=stringInfo.replace('jonins','jon&ins', 2) 3 print(stringInfo)
5.split
split() 通過指定分隔符對字串進行切片,如果引數num 有指定值,則僅分隔 num 個子字串。返回分割後的字串列表。
語法格式:
1 myStr.split(str, num)
說明:
myStr:指定分割的字串。
str:分隔符,預設為所有的空字元,包括空格、換行(\n)、製表符(\t)等。
num:分割次數。
示例如下:
1 stringInfo = 'jonins jonins jonins jonins ' 2 stringInfoList=stringInfo.split(' ', 2) 3 print(stringInfoList)
6.capitalize
capitalize() 方法將字串的第一個字母變成大寫,其他字母變小寫。示例如下:
1 stringInfo = 'jonins jonins jonins jonins ' 2 stringInfo=stringInfo.capitalize() 3 print(stringInfo)
7.title
title() 方法返回"標題化"的字串,所有單詞的首個字母轉化為大寫,其餘字母均為小寫。示例如下:
1 stringInfo = 'jonins jonins jonins jonins ' 2 stringInfo=stringInfo.title() 3 print(stringInfo)
8.startswith&endswith
startswith() 方法用於檢查字串是否是以指定子字串開頭,如果是則返回 True,否則返回 False。如果引數 start 和 end 指定值,則在指定範圍內檢查。
endswith() 方法用於判斷字串是否以指定字尾結尾,如果以指定字尾結尾返回True,否則返回False。如果引數 start 和 end 指定值,則在指定範圍內檢查。
語法格式:
1 myStr.startswith(str, start,end)#檢測指定開始 2 myStr.endswith(str, start,end)#檢測指定結尾
說明:
myStr:指定檢索的字串。
str:該引數可以是一個字串或者是一個元素。
start:字串中的開始位置。
end:字元中結束位置。
示例如下:
1 stringInfo = 'hello jonins' 2 startFlag=stringInfo.startswith('hel') 3 endFlag=stringInfo.endswith('ins') 4 print(startFlag) 5 print(endFlag)
9.lower&upper
lower() 方法轉換字串中所有大寫字元為小寫。
upper() 方法將字串中的小寫字母轉為大寫字母。
示例如下:
1 stringInfo = 'heLlO jOnInS' 2 lowerStr=stringInfo.lower() 3 upperStr=stringInfo.upper() 4 print(lowerStr) 5 print(upperStr)
10. ljust& rjust& center
ljust() 方法返回一個原字串左對齊,並使用空格填充至指定長度的新字串。如果指定的長度小於原字串的長度則返回原字串。
rjust() 方法返回一個原字串右對齊,並使用空格填充至長度 width 的新字串。如果指定的長度小於字串的長度則返回原字串。
center() 方法返回一個指定的寬度 width 居中的字串,fillchar 為填充的字元,預設為空格。
語法格式:
1 myStr.ljust(width,fillchar) 2 myStr.rjust(width,fillchar) 3 myStr.center(width,fillchar)
說明:
myStr:指定需對齊的字串。
width:指定字串長度。
fillchar:填充字元,預設為空格。
示例如下:
1 stringInfo = 'jonins' 2 ljustStr=stringInfo.ljust(10)#左對齊 3 rjustStr=stringInfo.rjust(10)#右對齊 4 centerStr=stringInfo.center(10)#居中 5 print('-%s-'%ljustStr) 6 print('-%s-'%rjustStr) 7 print('-%s-'%centerStr)
11.lstrip&rstrip&strip
lstrip() 方法用於截掉字串左邊的空格或指定字元(預設為空格)。
rstrip() 方法用於刪除字串末尾的指定字元(預設為空格)。
strip() 方法用於移除字串頭尾指定的字元(預設為空格)或字元序列。該方法只能刪除開頭或是結尾的字元,不能刪除中間部分的字元。
語法格式:
1 myStr.lstrip(chars)#刪除左邊的某字元 2 myStr.rstrip(chars)#刪除右邊的某字元 3 myStr.strip(chars)#刪除兩端的某字元
說明:
myStr:指定檢索的字串。
chars:指定移除的字元。
示例如下:
1 myStr = 'jonins' 2 lstripStr=myStr.lstrip() 3 rstripStr=myStr.rstrip() 4 stripStr=myStr.strip() 5 print('-%s-'%lstripStr) 6 print('-%s-'%rstripStr) 7 print('-%s-'%stripStr)
12.partition&rpartition
partition() 方法用來根據指定的分隔符將字串進行分割。如果字串包含指定的分隔符,則返回一個3元的元組,第一個為分隔符左邊的子串,第二個為分隔符本身,第三個為分隔符右邊的子串。
rpartition() 方法類似於 partition() ,不過是從右開始。示例如下:
1 myStr = 'my name is jonins' 2 strTuple=myStr.partition('name') 3 print(strTuple)
13.splitlines
splitlines() 方法按照行('\r', '\r\n', \n')分隔,返回一個包含各行作為元素的列表,如果引數 keepends 為 False,不包含換行符,如果為 True,則保留換行符。
語法格式:
1 myStr.splitlines([keepends])
說明:
myStr:指定分割的字串。
keepends :預設為 False,不包含換行符,如果為 True,則保留換行符。
示例如下:
1 myStr = 'hello \n jonins' 2 strList=myStr.splitlines() 3 print(strList)
14.isalpha&isdigit&isalnum&isspace
isalpha() 方法檢測字串是否只由字母組成。
isdigit() 方法檢測字串是否只由數字組成。
isalnum() 方法檢測字串是否由字母和數字組成。
isspace() 方法檢測字串是否只由空白字元組成
示例如下:
1 isalphaStr='abcd'.isalpha()#判斷是否只有字母 2 isdigitStr='1234'.isdigit()#判斷是否只有數字 3 isalnumStr='a1b2c3'.isalnum()#判斷是否只有字母和字母 4 isspaceStr=''.isspace()#判斷是否只有空白字元 5 print(isalphaStr) 6 print(isdigitStr) 7 print(isalnumStr) 8 print(isspaceStr)
15.join
join() 方法用於將序列中的元素以指定的字元連線生成一個新的字串。
語法格式:
1 str.join(sequence)
說明:
str:指定連線的字元。
sequence:要連線的元素序列。
示例如下:
1 strList=['my','name','is','jonins'] 2 str=' ' 3 stringInfo=str.join(strList) 4 print(stringInfo)
列表常用操作(List)
1.新增元素(append&extend&insert)
append() 方法用於在列表末尾新增新的物件。
extend() 函式用於在列表末尾一次性追加另一個序列中的多個值(用新列表擴充套件原來的列表)。
insert() 函式用於將指定物件插入列表的指定位置。
示例如下:
1 A=['1','2','3','4'] 2 A.append('5')#尾部追加一個元素 3 print(A) 4 B=['101','102','103'] 5 B.extend(A)#尾部追加一個集合 6 print(B) 7 B.insert(2,'INSERT')#在下標2處追加元素 8 print(B)
2.修改元素
修改元素的時候,要通過下標來確認要修改那個元素,然後才能進行修改,示例如下:
1 A=['1','2','3','4'] 2 A[0]='01' 3 print(A)
3.查詢元素(in¬ in&index&count)
可以使用 python運算子( in 、 not in ) 來判斷列表是否存在指定的元素,示例及說明如下:
in (包含) :如果存在那麼結果為Ture,否則為False。
not in (不包含) :如果不存在那麼結果為Ture,否則為False。
1 A=['1','2','3','4'] 2 flag1='2' in A 3 flag2='2' not in A 4 print(flag1) 5 print(flag2)
也可以使用python提供的 index 和 count 方法實現檢測,具體使用方式與 字串中使用index和count方法的用法相同 ,示例及說明如下:
index() 方法用於從列表中找出某個值第一個匹配項的索引位置。
count() 方法用於統計某個元素在列表中出現的次數。
1 A=['1','2','3','4'] 2 flag1=A.index('3') 3 flag2=A.count('3') 4 print(flag1) 5 print(flag2)
4.刪除元素(del&pop&remove)
del :根據下標進行刪除。
pop :刪除最後一個元素。
remove :根據元素的值進行刪除。
示例如下:
1 A=['1','2','3','4','5'] 2 del A[0]#根據下標刪除元素 3 A.pop()#刪除最後一個元素 4 A.remove('3')#根據元素值刪除元素 5 print(A)
5.排序(sort&reverse)
sort() 方法用於對原列表進行排序,如果指定引數,則使用比較函式指定的比較函式。而 reverse() 方法用於反向列表中元素(逆置)。
語法格式:
1 list.sort(cmp=None, key=None, reverse=False)
說明:
cmp:可選引數, 如果指定了該引數會使用該引數的方法進行排序。
key:主要是用來進行比較的元素,只有一個引數,具體的函式的引數就是取自於可迭代物件中,指定可迭代物件中的一個元素來進行排序。
reverse:排序規則, reverse = True 降序, reverse = False 升序(預設)。
示例如下:
1 A=['1','2','5','4','3'] 2 A.reverse()#列表逆置 3 print(A) 4 A.sort()#列表升序排序 5 print(A) 6 A.sort(reverse=True)#列表降序排序 7 print(A)
元組常用操作(Tuple)
元組內建的函式 index 和 count ,它們的 用法與字串和列表中的用法相同 。
字典常用操作(Dictionary)
1.修改元素
字典中的每個元素只要通過key(鍵)找到,即可修改。示例:
1 info={'name':'jonins','age':'18'} 2 info['age']='20' 3 print(info)
2.新增元素
當指定key(鍵)來訪問元素時若該鍵不存,則會報錯。如果要新增元素,可以使用:
1 變數名['鍵']=資料
的方式,當鍵不存在時,就會新增這個元素。示例如下:
1 info={'name':'jonins','age':'18'} 2 info['id']='1001' 3 print(info)
3.刪除元素(del&clear)
del 可以刪除指定的元素,也可刪除整個字典,刪除整個字典後不允許訪問字典,否則會報錯。
clear() 方法可以清空整個字典,允許清口後訪問字典。
示例如下:
1 infoA={'name':'jonins','age':'18','id':'1001','sex':'man'} 2 infoB={'name':'jonins','age':'18','id':'1001','sex':'man'} 3 del infoA['id'] 4 print(infoA) 5 del infoA#刪除後,不能訪問,否則會報錯 6 infoB.clear(); 7 print(infoB)
4.判斷鍵(in¬ in)
可以使用 python運算子( in、not in ) 來 判斷key(鍵)是否存在 ,示例及說明如下:
in (包含) :如果存在那麼結果為Ture,否則為False。
not in (不包含) :如果不存在那麼結果為Ture,否則為False。
1 info={'name':'jonins','age':'18','id':'1001','sex':'man'} 2 print('name' in info) 3 print('name' not in info)
5.其它內建及常用函式
len() 方法用於測量字典中的鍵值對個數。
keys() 方法返回一個包含字典所有key(鍵)的列表。
values() 方法返回一個包含字典所有value(值)的列表。
items() 方法返回一個包含所有(key,value)元組的列表。
示例如下:
1 info={'name':'jonins','age':'18','id':'1001','sex':'man'} 2 print(len(info)) 3 print(info.keys()) 4 print(info.values()) 5 print(info.items())
公共方法
運算子
注意 : in 和 not in 在對字典操作時,判斷的是 字典的key(鍵) 。
內建函式
結語
若無特殊說明,文章內的示例和說明,預設適用於 Python3 並不一定兼容於Python2。
作者Python直譯器為 Python3.6 版本。