0
How can I find the longest word , and print it in python?
Given a text as input, find and output the longest word. Sample Input this is an awesome text Sample Output awesome
4 Respostas
+ 2
# Function to print the longest
# word in given sentence
def largestWord(s):
# Sort the words in increasing
# order of their lengths
s = sorted(s, key = len)
# Print last word
print(s[-1])
# Driver Code
if __name__ == "__main__":
# Given string
s = "this is an awesome text"
# Split the string into words
l = list(s.split(" "))
largestWord(l)
+ 2
Vishal G
Nice, but what if there are two words with the same length?
+ 1
1) Split the string with the text to a list with the texts words as elements, here called txt (lst = txt.split()).
2) Find a way to get the max length for the words in the list (maxlength = max(map(len, lst))).
3) Find way to pick out all the words whos length is equal to the max length (res = [wd for wd in lst if len(wd) == maxlenth]).
4) print the result (print(res)).
0
@ Per Bratthammar
Whats the solution?