1.字符串的匹配 s="hjeallo jeapedu.com" sub= "jeap" i=0 while i<=len(s)-len(sub): j=0 c=0 while j<len(sub): if s[i+j]==sub[j]: c=c+1 j=j+1 if c==len(sub): print s[i],s[i+1],s[i+2],s[i+3] i=i+1 2.#python获取字符串中的子串 s="hello jeweixinhao:Jiangge1206du" head="je" tail="du" i=0 ch=0 ph=0 while i<=len(s)-len(head): j=0 a=0 while j<len(head): if s[i+j]==head[j]: #匹配 a=a+1#累计首部的长度 j=j+1 j=0 #初始化 b= 0 while j < len(tail): if s[i + j] == tail[j]: b = b+ 1 j = j + 1 if a==len(head): ch=i #确定首字母的位置 if b==len(tail): ph=i #确定尾字母的第一个的位置 i=i+1 print ch, ph sub="" #字符串存储的空串 k=ch+len(head) #找到要取子串的第一个位置 while k<ph: sub=sub+s[k] k=k+1 print sub 3.#难度稍微升级,寻找网站(字符串提取) s="welcome to visit my websit http://www.baidu.com a.com cx.com http://www.jiangge.com hello" print s head="http" tail=".com" i=0 ph=0#头的位置 pt=0 pre=0 #用来标记头的位置 while i<=len(s)-len(head): j=0 c=0 while j<len(head): if s[i+j]==head[j]: c=c+1 j=j+1 j = 0 d = 0 while j < len(tail): if s[i + j] == tail[j]: d = d+ 1 j = j + 1 if c==len(head): ph=i print "ph =",ph, if d== len(tail): pt = i print "pt =", pt, if ph<pt and pre!=ph:#遍历到尾部就把网址打印出来,进行判断,当与暂存的头相同时不再打印 sub="" k=ph while k<=pt+len(tail): sub=sub+s[k] k=k+1 pre=ph #暂存头的位置 print sub i=i+1
python编写代码用来提取字符串
最新推荐文章于 2022-09-25 10:11:08 发布