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
JavaScript
x
14
14
1
def splitword (ch,t):
2
i=0
3
while len(ch)!=-1:
4
if ch[i]== " " :
5
t.append(ch[0:i])
6
ch=ch.replace(ch[0:i],"")
7
else :
8
i=i+1
9
10
t=[]
11
ch = "promotion bac 2019"
12
splitword (ch,t)
13
print(t)
14
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.