for example i have this string : ch = “promotion bac 2019” and an empty list : t=[] i want to make the list get each word separately using the empty spaces result will be : t=[“promotion”,”bac”,”2019″] i tried deleting each word from the string after storing it in the list but i didn’t work properly . dont mind looking at my code its really bad
def splitword (ch,t): i=0 while len(ch)!=-1: if ch[i]== " " : t.append(ch[0:i]) ch=ch.replace(ch[0:i],"") else : i=i+1 t=[] ch = "promotion bac 2019" splitword (ch,t) print(t)
Advertisement
Answer
here the fixes for your code
def splitword (ch,t): i=0 while i != len(ch): if ch[i]== " " : t.append(ch[0:i]) ch=ch.replace(ch[0:i+1],"") # need to add 1 for the end position i = 0 # reset position else : i=i+1 if ch: t.append(ch) # add the last word t=[] ch = "promotion bac 2019" splitword (ch,t) print(t)
But from my side of view the @Sayse has gave you good advice about the split
function.