Python Program to Find the Longest Word in a Sentence
Beginner · Strings
This program finds the longest word in a sentence and its length. It goes through the words one by one and remembers the longest one seen so far.
Program
longest_word.py
sentence = "Python makes programming enjoyable for everyone" # or: sentence = input("Enter a sentence: ")
words = sentence.split()
longest = words[0]
for word in words:
if len(word) > len(longest):
longest = word
print("Sentence:", sentence)
print("Longest word:", longest)
print("Length:", len(longest))
Output
Sentence: Python makes programming enjoyable for everyone Longest word: programming Length: 11
How it works
split()breaks the sentence into a list of words.longeststarts as the first word and is replaced whenever a longer word turns up.- Using
>rather than>=means that when two words tie, the first one is kept. - Punctuation counts as part of a word here, so strip it first if the sentence has commas or full stops, as the second alternative does.
Other ways to write it
Using max() with key=len
Using max() with key=len
sentence = "Python makes programming enjoyable for everyone"
words = sentence.split()
longest = max(words, key=len)
shortest = min(words, key=len)
print("Longest word:", longest, "with", len(longest), "letters")
print("Shortest word:", shortest, "with", len(shortest), "letters")
Output
Longest word: programming with 11 letters Shortest word: for with 3 letters
key=len tells max() and min() to compare the words by their length; on a tie they return the first word.
All the longest words when there is a tie
All the longest words when there is a tie
import string
sentence = "Tea, coffee or juice: choose a drink."
words = [w.strip(string.punctuation) for w in sentence.split()]
most = max(len(w) for w in words)
winners = [w for w in words if len(w) == most]
print("Words:", words)
print("Longest length:", most)
print("Longest words:", winners)
Output
Words: ['Tea', 'coffee', 'or', 'juice', 'choose', 'a', 'drink'] Longest length: 6 Longest words: ['coffee', 'choose']
strip(string.punctuation) removes punctuation from the ends of each word. The program then finds the greatest length and keeps every word that has it.
Try it yourself
Use a sentence where two words share the longest length and see which one the main program picks.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises