[Tutor] avoid split function
Chad Crabtree
flaxeater at yahoo.com
Fri Aug 13 16:33:36 CEST 2004
Well I'm abashed. I wrote it out as a long string of code then put
it
into a function without really thinking it through. Thank you for
you
critique. I didn't even think of the empty string issue. Here's a
better one with the additional error checking
a="This is a test"
def split(astr):
m=[]
temp=""
if astr=='':
return []
for l in astr:
if l==" ":
m.append(temp)
temp=""
else:
temp=temp + l
m.append(temp)
return m
####output####
>>> ['This', 'is', 'a', 'test']
[]
['this', 'might', 'be', 'a', 'test', 'I', "don't", 'know']
Kent Johnson wrote:
> Thank you for showing the best way to iterate over a string! But be
> careful of the boundary conditions. With your definition, splitting
an
> empty string returns a list containing an empty string (split('')
==
> ['']) whereas splitting an empty string with the system split
returns
> an empty list (''.split() == [])
>
> Also mind your names - your function arg is named 'string' but your
> loop iterates over 'a'.
>
> Kent
>
> At 08:29 PM 8/12/2004 -0700, Chad Crabtree wrote:
>
>> Just thought I'd give my take without index counting.
>> a="This is a test"
>> def split(string):
>> m=[]
>> temp=""
>> for l in a:
>> if l==" ":
>> m.append(temp)
>> temp=""
>> else:
>> temp=temp + l
>> m.append(temp)
>> return m
>> print split(a)
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
__________________________________
Do you Yahoo!?
Yahoo! Mail is new and improved - Check it out!
http://promotions.yahoo.com/new_mail
More information about the Tutor
mailing list