Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the longest word in each sentence

Extract the longest word from each sentence in a text, preserving case and choosing the first occurrence on ties.

Python practice25 minString PatternsAdvancedLast updated March 18, 2026

Problem statement

Given a string containing one or more sentences, identify the longest word in each sentence. Sentences are delimited by the punctuation characters '.', '!', or '?'. Words are contiguous sequences of alphabetic characters (a-z, A-Z). For each sentence that contains at least one word, return the first word with maximal length in that sentence, preserving the original word's casing. If the input contains no words, return an empty list.

Task

Implement a function that splits text into sentences and returns a list containing the longest word from each sentence. If multiple words tie for longest, return the first one. Ignore non-alphabetic characters when defining words.

Examples

Two sentences

Input

Hello world! This is a test.

Output

['Hello', 'This']

First sentence: 'Hello' and 'world' tie at length 5, but 'Hello' appears first. Second sentence: 'This' and 'test' tie at length 4, 'This' appears first.

Input format

A single string containing one or more sentences.

Output format

A Python list of strings. Each element is the longest word from the corresponding sentence (first occurrence if tie).

Constraints

0 <= len(text) <= 100000. Use O(n) time where n is the length of the text. Only letters are part of words; punctuation and digits separate words.

Samples

Sample 1

Input

The quick brown fox jumps over the lazy dog.

Output

['quick']

Only one sentence; 'quick' and 'brown' tie at length 5 but 'quick' appears first.