How to find the longest word with python?
Asked Answered
C

5

1

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'
Creaturely answered 28/7, 2009 at 9:10 Comment(2)
This is probably the most difficult to understand question I've ever read. You are looking for the longest word in a given string, so in your example this would be 'aaa', right?! And you want to get it from a single expression using built-ins, and without creating an own function or class. Is that the essence of your question?Seigneury
@LarsOn: Please do not comment on your own question. Please delete the comment and UPDATE the question with the new information.Suboxide
D
39

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.

Dissatisfy answered 28/7, 2009 at 9:15 Comment(0)
S
2

Here is one from the category "How difficult can you make it", also violating the requirement that there should be no own class involved:

class C(object): pass
o = C()
o.i = 0
ss = 'a aa aaa aa'.split()
([setattr(o,'i',x) for x in range(len(ss)) if len(ss[x]) > len(ss[o.i])], ss[o.i])[1]

The interesting bit is that you use an object member to maintain state while the list is being computed in the comprehension, eventually discarding the list and only using the side-effect.

But please do use one of the max() solutions above :-) .

Seigneury answered 28/7, 2009 at 9:53 Comment(1)
Ah, even better: o.i = ''; ([setattr(o,'i',x) for x in s.split() if len(x) > len(o.i)], o.i)[1]Seigneury
P
1

I thought it meant more like (code below) which outputs the longest word in the string. In this case it is "sentence" however, simply change return(len(s)) which would output howmany characters are in the longest word which would be 8.

def longest_word(text):
    s = max(text.split(), key = len)
    return(s)

if __name__ == "__main__":
    print(longest_word("This is a sentence with words and such."))
Paxwax answered 5/9, 2021 at 0:22 Comment(0)
G
0

Another way to find longest word in string:

a="a aa aaa aa"
b=a.split()
c=sorting(b,key=len)
print(c[-1])    
Gastroenterostomy answered 21/1, 2017 at 10:44 Comment(0)
H
0
def largest_word(sentence):
    split_sentence = sentence.split(' ')
    largest_word = ''
    for i in range(len(split_sentence)):
        if len(split_sentence[i]) > len(largest_word):
           largest_word = split_sentence[i]
    print(largest_word)


sentence = "Improve your coding skills with python"

largest_word(sentence)
Hajji answered 14/8, 2018 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.