[Tutor] avoid split function

Kent Johnson kent_johnson at skillsoft.com
Fri Aug 13 16:54:57 CEST 2004


As long as I am being picky, I'll point out that there are quite a few 
special cases to consider. I don't think either David or Chad's solution 
duplicates the behavior of string.split() on all of them. (Hmm, sounds like 
a good opportunity to learn about unittest :-)

 >>> 'abc  de'.split()  # Multiple spaces between words
['abc', 'de']

 >>> 'abc'.split()  # Just one word
['abc']

 >>> ''.split()  # Empty string
[]

 >>> 'abc  '.split()  # Trailing spaces
['abc']

 >>> '  abc'.split()  # Leading spaces
['abc']

Kent

At 07:33 AM 8/13/2004 -0700, Chad Crabtree wrote:
>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