How can I use python to find the longest word from a set of words? I can find the first word like this:
JavaScript
x
10
10
1
'a aa aaa aa'[:'a aa aaa aa'.find(' ',1,10)]
2
3
'a'
4
5
rfind is another subset
6
7
'a aa aaa aa'[:'a aa aaa aa'.rfind(' ',1,10)]
8
9
'a aa aaa'
10
Advertisement
Answer
If I understand your question correctly:
JavaScript
1
4
1
>>> s = "a aa aaa aa"
2
>>> max(s.split(), key=len)
3
'aaa'
4
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.