String splitting question

Max M maxm at mxm.dk
Wed Apr 9 10:03:11 CEST 2003


William Park wrote:
> Jim Shady <iamshady at rediffmail.com> wrote:

>>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?

> out = []
> for i in 'abcd/df/a/iiwk/abcdefghijkl/b/c'.split('/'):
>     out.append( (len(i), i) )
> print max(out)[1]

Or the ultra terse version, which basically does the same thing:

s = 'abcd/df/a/iiwk/abcdefghijkl/b/c'
print max([(len(sub), sub) for sub in s.split('/')])[-1]

-- 

hilsen/regards Max M Rasmussen, Denmark

http://www.futureport.dk/
Fremtiden, videnskab, skeptiscisme og transhumanisme





More information about the Python-list mailing list