[Tutor] avoid split function

Chad Crabtree flaxeater at yahoo.com
Fri Aug 13 17:49:56 CEST 2004


Kent Johnson wrote:

> 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
>
Not the complete functionality of ''.split() but close. 
And there is some unit tests right? I tried to be a bit more general
to 
add in optional separators.  I'm not sure why this got my goat.  It
was 
fun however.

def split(astr,sep=('','\n','\t',' ')):  
    m=[]
    temp=""
    if astr in  sep:
        return []
    for l in astr:
        if l in sep:
            m.append(temp)
            temp=""
        else:
            temp=temp + l
    m.append(temp)
    m=[x for x in m if x not in sep] #remove blank elements
    return m

print split('this is a test')
print split('abc,de',',')
print split('\n')
print split('    abc')
print split('\tabc')
print split('\nabc')
print split('abc  ')
print split('abc   de')
print split('')
print split("this might be a test I don't know")


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 


More information about the Tutor mailing list