views:

68

answers:

1

Hello everyone, I got stuck on this idea: how do I get the second longest word in a sentence ? I'm going to use it for an exit route in my code where the longest word might fail a test. Any ideas ? Thanks in advance.

+5  A: 

something like this:

second_longest = sorted(sentence.split(), key=len)[-2]

This is a pretty naive definition of word however, since it only splits on whitespace so any punctuation will be included as part of the words. You may want to filter the sentence to remove punctuation characters first.

Dave Kirby
@Dave Kirby, nice one. But my bad, I forgot to give the exact details in haste. My actual question involving this problem can be found at http://stackoverflow.com/questions/3595877/how-to-make-this-random-text-generator-more-efficient-in-python
@Dave Kirby, solved that problem sir, thanks again for initiation idea.