How to find the longest word with python?

前端 未结 4 1366
萌比男神i
萌比男神i 2020-12-11 12:34

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

         


        
4条回答
  •  孤街浪徒
    2020-12-11 13:21

    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.

提交回复
热议问题