String splitting question

Klaus Alexander Seistrup spam at
Wed Apr 9 09:08:09 CEST 2003

Jim Shady wrote:

> I have a string:
> abcd/df/a/iiwk/abcdefghijkl/b/c
> I need to get the longest string between the /s of the string.
> For example, longest_str() for the above line should return
> 'abcdefghijkl'. How do I go about doing this?



def longest_str(s):
    cache = {}
    words = s.split('/')
    for word in words:
        wlen = len(word)
        if cache.has_key(wlen):
            cache[wlen] = [word]
        # end if
    # end for
    return cache[max(cache.keys())]
# end def longest_str


Apply sanity checks as needed.

  // Klaus

 ><> 	unselfish actions pay back better

More information about the Python-list mailing list