LearnFrenzy
Sign in Take a free test

Strings · Strings Coding Problems · Question 7

Find the longest word in a sentence in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Find the longest word in a sentence (ignoring punctuation) and its length. If several are equally long, take the first.

Solution
main.py Run
sentence = "Practice makes progress, not perfection!"
words = [w.strip(".,!?") for w in sentence.split()]
longest = max(words, key=len)              # max returns the FIRST of equal maxima
print(longest, len(longest))
print(sorted(words, key=len, reverse=True)[:2])

Output Verified by running it on Python 3

perfection 10
['perfection', 'Practice']

strip(".,!?") removes punctuation at the ends of each word. max(…, key=len) compares lengths; sorted is stable, so "Practice" stays ahead of "progress".

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links