1 #字符串常用方法 2 s='apple,peach,banana,peach,pear' 3 #返回第一次出現的位置 4 print(s.find('peach')) 5 #指定位置開始查找 6 print(s.find('peach',7)) 7 #指定范圍中進行查找 8 print(s.find('peach',7,20)) 9 #從字符串尾部向前查找 10 print(s.rfind('p')) 11 #返回首次出現的位置 12 print(s.index('p')) 13 #統計子字符串出現的次數 14 print(s.count('p')) 15 16 #Python內置函數和內置對象的方法,運行速度快,並且運行穩定。 17 from string import ascii_letters 18 from random import choice 19 from time import time 20 21 letters = ''.join([choice(ascii_letters) for i in range(999999)]) 22 def positions_of_character(sentence,ch): #使用字符串呢對象的find()方法 23 result=[] 24 index=0 25 index=sentence.find(ch,index+1) 26 while index !=-1: 27 result.append(index) 28 index=sentence.find(ch,index+1) 29 return result 30 31 def demo(s,c): #普通方法,逐個字符比較 32 result=[] 33 for i,ch in enumerate(s): 34 if ch==c: 35 result.append(i) 36 return result 37 38 start = time() 39 positions_of_character(letters,'a') 40 print(time()-start) #0.008852958679199219 41 42 start=time() 43 p=demo(letters,'a') 44 print(time()-start) #0.0904378890991211 45 46 #split()從字符串左端開始將其分隔成多個字符串,並返回包含分隔結果的列表 47 48 #rsplit()從字符串右端開始將其分隔成多個字符串,並返回包含分隔結果的列表 49 50 #partition()、rpartition()用來以指定字符串為分隔符將原字符串分隔為3部分,即分隔符之前的字符串、分隔符字符串和分隔符之后的字符串。如果指定的分隔符不再原字符串中,則返回原字符串和兩個空字符串 51 52 s='apple,peach,banana,pear' 53 li=s.split(',') 54 print(li) 55 li2=s.partition(',') #從左側使用逗號進行切分 56 print(li2) 57 #('apple,peach,banana,pear', '', '') 58 li3=s.rpartition(',') 59 print(li3) 60 #('apple,peach,banana', ',', 'pear') 61 li4=s.rpartition('banana') #使用字符串作為分隔符 62 print(li4) 63 # ('apple,peach,', 'banana', ',pear') 64 s1='2014-10-31' 65 t=s1.split('-') 66 print(t) 67 # [2014, 10, 31] 68 li5=list(map(int,t)) #將分隔結果轉換為整數 69 print(li5) 70 # ['hello', 'world', 'My', 'nname', 'is', 'zWrite'] 71 72 #對於split()和rsplit()方法,如果不知定分隔符,則字符串中的任何空白字符(包括空格、換行符、制表符等)的連續出現都將被認為是分隔符,返回包含最終分隔結果的列表 73 s2='hello world\n\n My nname is zWrite' 74 li6=s2.split() 75 print(li6) 76 # ['hello', 'world', 'My', 'name', 'is', 'zWrite'] 77 s3='\n\nhello world\n\n\n My name is zWrite ' 78 li7=s3.split() 79 print(li7) 80 # ['hello', 'world', 'My', 'name', 'is', 'zWrite'] 81 s4='\n\nhello\t\t world \n\n\n My name is zWrite ' 82 li8=s4.split() 83 print(li8) 84 # ['hello', 'world \n\n\n My name is zWrite'] 85 86 #split()與rsplit()方法允許指定最大分隔次數 87 s5='\n\nhello\t\t world \n\n\n My name is zWrite' 88 print(s5.split(maxsplit=1)) #分隔1次 89 li9=s5.rsplit(maxsplit=1) 90 print(li9) 91 # ['\n\nhello\t\t world \n\n\n My name is', 'zWrite'] 92 li10=s5.split(maxsplit=20) #最大分隔次數大於實際可分隔次數時,自動忽略 93 print(li10) 94 #['hello', 'world', 'My', 'name', 'is', 'zWrite']