Hello guys. In a given string, how can one fine and output the longest word by writing a program in python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Hello guys. In a given string, how can one fine and output the longest word by writing a program in python?

22nd Dec 2020, 2:39 PM
Mas'ud Saleh
Mas'ud Saleh - avatar
10 Answers
+ 9
You can search for codes in the Code section : https://code.sololearn.com/cjClje60YyXV/?ref=app
22nd Dec 2020, 2:45 PM
Alphin K Sajan
Alphin K Sajan - avatar
+ 6
print([ st if len(st) == max(s.split(),key=len) for st in s.split()]) edit: print([t for t in s.split() if len(t) == len(max(s.split(), key=len))])
22nd Dec 2020, 4:08 PM
Oma Falk
Oma Falk - avatar
+ 5
Jan Markus dss verwechselt ich immer Thanks for showing correct solution.
22nd Dec 2020, 6:04 PM
Oma Falk
Oma Falk - avatar
+ 3
The clasic algorithmus Mas-ud Al-hassan for find out the maximum is to declare my first item as maximum and check items of the list. If an item will be greather then will be set to the maximum. short solution for longest word: https://code.sololearn.com/cd89N09f7P0R/?ref=app
22nd Dec 2020, 9:12 PM
JaScript
JaScript - avatar
+ 2
Have a look at the built-in max function and use key=len.
22nd Dec 2020, 3:48 PM
rodwynnejones
rodwynnejones - avatar
+ 1
@Jan Markus True...but that is what was requested in the original post "longest word".....this would get multiple instances using the max and list comprehension:- mystring = input() mylist = [x for x in mystring.split() if len(x) == len(max(mystring.split(), key=len))] print(*mylist)
22nd Dec 2020, 4:10 PM
rodwynnejones
rodwynnejones - avatar
0
you would use the len function in conjunction with the max function to get the answer. for strings it goes by capatilazation so be aware of that
24th Dec 2020, 1:27 AM
Avalon
0
or you could use the .split function and split at every instance of a space. Then split each word into an individual array or list. then find the word with the longest array and return that
24th Dec 2020, 1:28 AM
Avalon
0
This was my solution. There might be a better way, but this uses just the skills, functions, and methods taught up to that project: https://code.sololearn.com/c3A23A20a8A3
26th Jul 2021, 1:20 AM
Josh Ritz
- 2
Hf
24th Dec 2020, 7:55 AM
ツ P R I N C E└∵┐NA I Nツ
ツ P R I N C E└∵┐NA I Nツ - avatar