Longest and shortest word

EasyString Programs · 7 of 106

Write a Python program to find the longest and the shortest word in a string.

Advertisement
Input
"Python makes string handling easy"
Output
Longest: handling
Shortest: easy

Approach

  1. Split into words and use max / min with key=len.

Solution

Python
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.

More string programs

← All 106 String Programs

Leave a Comment