String splitting question

Giles Brown giles_brown at hotmail.com
Wed Apr 9 08:33:31 EDT 2003


iamshady at rediffmail.com (Jim Shady) wrote in message news:<9afd3f36.0304082245.33670341 at posting.google.com>...
> 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?

You can split the string into a list of (length, substring) tuples.
The 'max' of these tuples will be the longest substring.

Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> def longest(s, sep='/'):
	return max([(len(sub), sub) for sub in s.split(sep)])[1]

>>> longest('abcd/df/a/iiwk/abcdefghijkl/b/c')
'abcdefghijkl'
>>> 

Giles




More information about the Python-list mailing list