String splitting question

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Apr 9 04:38:40 EDT 2003


Max M <maxm at mxm.dk> wrote in 
news:LqQka.8341$y3.1005660 at news010.worldonline.dk:

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

It might be worth noting that if there are multiple strings of the same 
longest length, these solutions both give you the last one.
The variant below will give you a list of all the longest strings from 
which you can select first, last or any other combination.

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

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list