Python字串分割函式
阿新 • • 發佈:2019-01-29
Python學習之字串分割
設計一個函式把一個含有空格的字串分割成幾個字串
def splice1(temp): temp=temp.strip() while temp.find(' ')!=-1: temp1=temp[:temp.find(' ')] print temp1.strip() temp=temp[temp.find(' ')+1:].strip() print temp[temp.find(' ')+1:] s2=raw_input('Plz input a string:') splice1(s2)
例子:
Plz input a string: i hiue iuei liui MIUI 9898&& *(((( LII ELI LE IE KJIjiJIJIE 179080 08098
ihiue
iuei
liui
MIUI
9898&&
*((((
LII
ELI
LE
IE
KJIjiJIJIE
17908008098
增強版的字串切割函式:
src為要切割的字串,sep為切割字元
def my_split(src,sep): src=src.strip() a=src.find(sep) w1=src[:a] print w1 b=a n=len(sep) while b<=len(src) and b!=-1: while src[a:a+n]==sep: a=a+n b=src.find(sep,a) if b!=-1: print src[a:b] else: print src[a:b] a=b s=raw_input('Plz input your string need to splitted:') sp=raw_input('Plz input your splitting string:') my_split(s,sp)
例子:
Plz input your string need to splitted: jiji....sjeij...2....42.s.r..fs/.er.;s.plep.s;e,;l;slflep...s,eplps,e.pp..koio
Plz input your splitting string:..
jiji
sjeij
.2
42.s.r
fs/.er.;s.plep.s;e,;l;slflep
.s,eplps,e.pp
koi