- 4
Given a text as input, find and output the longest word. Sample Input this is an awesome text Sample Output awesome
Longest word
6 Answers
+ 7
Atul ,
certain
as Denise RoĂberg already mentioned: using split() is an easy and preferred way to split strings at a certain separator:
txt = 'this is my coding'
lst = txt.split() # ['this', 'is', 'my', 'coding']
for word in lst:
....
+ 6
Tia ,
as Atul already mentioned, you should show us your attempt first.
to give you some hints to start:
âŞď¸take an input
âŞď¸split the input at the position of spaces to a list
âŞď¸create a variables as buffer for the longest word and the length of it
âŞď¸iterate through the list, that gives you one word in each iteration
âŞď¸compare the word length given in the loop with the length in the buffer
âŞď¸if new word is longer than word in buffer, replace word and length in buffer
âŞď¸if iteration is terminated, the longest word is in the buffer.
âŞď¸print it out
+ 2
Post your code here
+ 2
Lothar do we need to split it into spaces or only using if will work?
+ 2
Atul Would be possible but the split function makes it easier.
+ 1
txt = input()
a= txt.split()
length=[len(i) for i in a]
maximum = max(length)
text_index = length.index(maximum)
print(a[text_index])
this code is wonderful :)