[Tutor] avoid split function

Alan Gauld alan.gauld at blueyonder.co.uk
Fri Aug 13 05:53:54 CEST 2004


> a = "This is a test"
> 
> for i in range(0,len(a)):
>      if a[i] == "  ":
>            print y
>      elif a[i] != "  ":
>              y.append(a[i])
>              m.append(y[0:])

Thiis is easier like this:

for i in a:
  if i == " ":
     print y
  else:
     y.append(i)
     m.append(y[:])   #not sure what you think this is doing!

> I wanted to push "This" in to m as m = ['This']
> I know i can do this using:
> 
> c = a.split()

OK, I'd suggest using while loops:

i = 0
while a[i]:
  while a[i] != " "
     m.append(a[i])
     i += 1
  y.append[m]
  i += 1

Which should give a list of lists in y

y => [[T,h,i,s],[i,s],....]

You could also use functional programming tools like list 
comprehensions I suspect.

Note that the code above is not tested, but hopefully 
its a starter.

Alan G.




More information about the Tutor mailing list