Find the Longest Word in a Sentence in Python
Splits a sentence into words and returns the longest one using the built-in max() function with len as the key.
Python code
11 linesdef find_longest_word(sentence: str) -> str:
words = sentence.split()
if not words:
return ""
return max(words, key=len)
if __name__ == "__main__":
test_sentence = "The quick brown fox jumps over the lazy dog"
longest = find_longest_word(test_sentence)
print(f"Longest word: '{longest}'")
print(f"Length: {len(longest)}")
Output
Longest word: 'quick'
Length: 5
How it works
The sentence.split() method splits the input string on whitespace, producing a list of words. The max() function with key=len compares words by their length and returns the longest one. The function returns an empty string for an empty input to avoid an unhandled ValueError. This approach is concise and uses only built-in functions, making it efficient and readable.
Common mistakes
- Forgetting to handle empty input, which causes max() to raise ValueError
- Using split(' ') instead of split() which can produce empty strings from multiple spaces
Variations
- Use a loop with a manual comparison if max() is not allowed or for additional logic like handling ties.
- Use sorted(words, key=len, reverse=True)[0] if you also need the second-longest word.
Real-world use cases
- Implementing a word-count feature that highlights the most prominent keyword in user-generated content.
- Building a text-analysis tool that identifies the longest term in a document for summarization tasks.
- Writing a game helper that finds the longest possible word from a given set of letters.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.