python : the longest word in a string
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
Seems like a very complicated way. A simple pythonic way would be:
def longest_word(s):
return max(s.split(), key=len)
Output:
>>> longest_word("ceci est un texte")
"texte"