Home > Enterprise >  python : the longest word in a string
python : the longest word in a string

Time:11-23

I'm developing a function that returns the longest word from a string, my code is :

def longestWord(sen):
    max = 1
    i = 0
    ind = 1
    while ind != 0 :
        if sen[i] == " ":
            i = i 1
        word = ""
        lenth = 0

        while(sen[i] != " " and i < len(sen)):
            word = word   sen[i]
            lenth = lenth 1
            if(lenth > max):
                max = lenth
                longestword = word
            i = i 1
            if i == len(sen)-1:
                ind = 0



    return longestword

print(longestWord("ceci est un texte"))

When I try to run it an error shows up saying that "string index out of range"

The error message:

Traceback (most recent call last):
      File "C:\Users\pc\PycharmProjects\pythonProject2\venv\tp2\longestWord.py", line 25, in <module>
        print(longestWord("ceci est un texte"))
      File "C:\Users\pc\PycharmProjects\pythonProject2\venv\tp2\longestWord.py", line 11, in longestWord
        while(sen[i] != " " and i < len(sen)):
    IndexError: string index out of range

CodePudding user response:

Seems like a very complicated way. A simple pythonic way would be:

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

Output:

>>> longestWord("ceci est un texte")
"texte"

CodePudding user response:

You can do this in one line

def longest_word(sentence): 
    return sorted(sencente.split(), key = lambda x: len(x))[-1]

print(longest_word("ceci est un texte"))

CodePudding user response:

If you want to capture the results in a list, because multiple words may be the same length.

def longest_words(sentence):
    words = sentence.split()
    maxlen = max(len(w) for w in words)
    return [w for w in words if len(w) == maxlen]

Or in one pass:

def longest_words(sentence):

    words = sentence.split()
    results = []
    maxlen = 0

    for w in words:

        curlen = len(w)

        if curlen > maxlen:
            results = [w]
            maxlen = curlen
        elif curlen == maxlen:
            results.append(w)

    return results

CodePudding user response:

Replace your function with this one :

def longestWord(string) :
    lettersCounter = 0
    result = ""
    for word in string.split() :
        if(len(word) > lettersCounter) :
            lettersCounter = len(word)
            result = word

    return result

print(longestWord("ceci est un texte"))

  • Related