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']