Find Longest Word

Find longest word in string.

IntermediatePhase 5 - Category 3: Word OperationsExample 4 of 10
find-longest-word.py
1# Take string input
2s = input("Enter a string: ")
3
4# Find longest word
5words = s.split()
6if len(words) > 0:
7 longest = max(words, key=len)
8 print(f"Longest word: {longest}")
9else:
10 print("No words found")

Output

Enter a string: Hello World Programming
Longest word: Programming

What's going on

Use max() with key=len to find longest.

Key Concepts:

max() finds maximum
key=len uses length for comparison
Returns longest word