[Python] python : the longest word in a string

Discussão em 'Python' iniciado por Stack, Agosto 12, 2025.

  1. Stack

    Stack Membro Participativo

    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+1
    word = ""
    lenth = 0

    while(sen != " " and i < len(sen)):
    word = word + sen
    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 != " " and i < len(sen)):
    IndexError: string index out of range

    Continue reading...

Compartilhe esta Página