How can I use python to find the longest word from a set of words? I can find the first word like this:
'a aa aaa aa'[:'a aa aaa aa'.find(' ',1,10)]
'a'
rfind is another subset
'a aa aaa aa'[:'a aa aaa aa'.rfind(' ',1,10)]
'a aa aaa'
Advertisement
Answer
If I understand your question correctly:
>>> s = "a aa aaa aa" >>> max(s.split(), key=len) 'aaa'
split() splits the string into words (seperated by whitespace); max() finds the largest element using the builtin len() function, i.e. the string length, as the key to find out what “largest” means.