- 1
How I can output the longest word in text?
Using the text as input, find and output the longest word. Sample input this is an awesome text Result example awesome Remember the split ('') method, which returns a list of words in a string. https://code.sololearn.com/co74yVYF71R2/?ref=app
8 Réponses
+ 10
Azizkxon Murotkhonov , you could do like:
- take input with input() function
- separate the sentence from input to a list by using split()
- sort the just created list by using a special argument for sorted that is a lambda function and sort by length of element
- after this the last element in the list is the longest word.
Happy coding!
+ 4
x="this is an awesome text"
y=x.split()
k=max(len(p) for p in y)
for i in y:
if len(i)==k:
print(i)
>>>>>>awesome
+ 3
Lothar Thanks, I have done this code
+ 3
Hope this helps
txt = input()
#your code goes here
longest = max(txt.split(), key=len)
print( longest )
+ 2
Using len function
+ 2
I wrote a code that can output multiple strings, and is till beginner frendly (since im also a beginner):
txt = input("str: ")
splitted_txt = txt.split()
char_numb = (len(p) for p in splitted_txt)
max_char_numb = [max(char_numb)]
for i in splitted_txt:
if len(i) in max_char_numb:
print(i)
0
#Solution_1
text = input (" ").split(" ")
text_dict = {}
text_list = []
for word in text:
text_dict[word] = len(word)
text_list.append(len(word))
for key,value in text_dict.items():
if value == max(text_list):
print (key)
#Solution_2
text = input (" ").split(" ")
text_dict = {}
text_list = []
for word in text:
text_dict[word] = len(word)
max_value = 0
max_key = " "
for key, value in text_dict.items():
if value > max_value:
max_key = key
max_value = value
print(max_key)
0
txt = input()
#your code goes here
y=txt.split(" ")
k=max(len(p) for p in y)
for i in y:
if len(i)==k:
print(i)