PDA

View Full Version : write a function that ignores ',' using Python



s1300045
August 31st, 2008, 04:46 AM
I am writing a function that will read in a string, dice it according to the commas, and store the result into a list.




def read(string):
a = []
tmp = ''
for i in string:
if i == ',':
a[len(a):]= [tmp]
tmp = ''
tmp = tmp + i
return a

  For now it's only reading things before the first comma into the list, can someone point out what I am doing wrong here? I just started learning Python on my own. It would be great if I can find some tutoring here. Thanks!

Wybiral
August 31st, 2008, 04:52 AM
Why not use the standard split function?



print "this,is,comma,separated".split(',')

s1300045
August 31st, 2008, 05:04 AM
I thought reinventing wheels could help me get familiar with Python, but hack, I didn't even know there's a split function! I'd still like to know what I am doing wrong though.

Thanks for answering!

ghostdog74
August 31st, 2008, 05:30 AM
I thought reinventing wheels could help me get familiar with Python, but hack, I didn't even know there's a split function! I'd still like to know what I am doing wrong though.

Thanks for answering!


without the split function, you can always use string fundamentals. The following use simple slicing and indexing.


s="one,two,three"
while 1:
if "," in s:
ind = s.index(",")
print s[:ind]
s=s[ind+1:]
else:
if s : print s
break

Quikee
August 31st, 2008, 10:35 AM
A little bit modified and it works fine:

def read(string):
a = []
tmp = ''
for i in string:
if i == ',':
a.append(tmp)
tmp = ''
else:
tmp = tmp + i
a.append(tmp)
return a

print read("a,b,c,ddd")


Add to the end of a list with append.