String splitting question
Jim Meyer
jmeyer at pdi.com
Wed Apr 9 11:21:21 EDT 2003
On Tue, 2003-04-08 at 23:45, 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?
Toss this one onto the heap; it feels a bit more pythonic and
straightforward than some of the solutions offered:
byLen = lambda a,b : cmp(len(a), len(b))
words = 'abcd/df/a/iiwk/abcdefghijkl/b/c'.split('/')
words.sort(byLen)
print words[-1]
Certainly not as clever as the solves authored by Peter Abel, William
Park, and Max M, but much more easily understood and maintained --
important if you ever want to leave a codebase behind without having to
leave the company. =]
BTW, if you're splitting on "/" because it's a path separator, you might
consider using os.sep instead; it makes your code a bit more portable.
Cheers!
--j
--
Jim Meyer, Geek at Large jmeyer at pdi.com
More information about the Python-list
mailing list