String splitting question

Peter Abel p-abel at t-online.de
Wed Apr 9 07:12:24 EDT 2003


Fred Gansevles <gansevle at ewi.utwente.nl> wrote in message news:<b70g6p$ecq$1 at netlx020.civ.utwente.nl>...
> Jim Shady wrote:
> 
> > Hello,
> > 
> > I am a beginner at Python and I just joined this group.
> > 
> > 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?
> > 
> > Thanks in advance.
> > 
> > Regards,
> > Jim
> 
> try this one:
> 
>         def ls(s, c='/'):
>             parts = s.split(c)
>             d = {}
>             for p in parts:
>                 if not d.has_key(len(p)):
>                     d[len(p)] = []
>                 d[len(p)].append(p)
>             k = d.keys()
>             k.sort()
>             return d[k[-1]]
> 
>         print ls('abcd/df/a/iiwk/abcdefghijkl/b/c')
> 
> it returns a list with the longest strings

Maybe one of the shortest possibilities - but not the most comprehensible - is:
>>> s='abcd/df/a/iiwk/abcdefghijkl/b/c'
>>> print max(map(lambda item:(len(item),item),s.split('/')))
(12, 'abcdefghijkl')
>>> 
Regards Peter




More information about the Python-list mailing list