Python Practice › String Programs › Program 7
Longest and shortest word
Write a Python program to find the longest and the shortest word in a string.
Input
"Python makes string handling easy"
Output
Longest: handling Shortest: easy
Approach
- Split into words and use
max/minwithkey=len.
Solution
text = "Python makes string handling easy"words = text.split()print("Longest:", max(words, key=len))print("Shortest:", min(words, key=len))Output
Longest: handling Shortest: easy
Line by line
Lines 3-4
key=len compares words by their length; on a tie, the first such word wins.
Learn the concept
New to this topic? Read the lesson, then come back.