Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - String

Find the longest word in a sentence - Python Program

Example 1 :

sentence = "Python is very powerful" words = sentence.split() print(max(words, key=len))

Output

 
OUTPUT  :
powerful

Example 2 :

def find_longest_word(sentence): """ Finds the longest word in a given sentence. Args: sentence: The input sentence string. Returns: The longest word found in the sentence. """ # Split the sentence into individual words based on whitespace. # The split() method returns a list of words. words = sentence.split() # Handle the case of an empty sentence to prevent errors. if not words: return "" # Use the max() function with the key argument set to len. # This tells max() to compare words based on their length, # returning the word with the maximum length. longest_word = max(words, key=len) return longest_word # Example usage: input_sentence = "The quick brown fox jumped over the lazy dog." longest_word = find_longest_word(input_sentence) print(f"The longest word in the sentence is: {longest_word}") input_sentence_2 = "Python is a versatile programming language." longest_word_2 = find_longest_word(input_sentence_2) print(f"The longest word in the sentence is: {longest_word_2}") # Example with punctuation input_sentence_3 = "Hey!! there, How is it going????" longest_word_3 = find_longest_word(input_sentence_3) print(f"The longest word in the sentence is: {longest_word_3}") # Example with an empty sentence input_sentence_4 = "" longest_word_4 = find_longest_word(input_sentence_4) print(f"The longest word in the sentence is: {longest_word_4}")

Output

 
OUTPUT  :
The longest word in the sentence is: jumped
The longest word in the sentence is: programming
The longest word in the sentence is: going????
The longest word in the sentence is: 

Explanation:

find_longest_word(sentence) function:

  • Takes a sentencestring as input.
  • Uses split()to divide the sentence into a list of words, where whitespace acts as the delimiter.
  • If the list of words is empty (meaning the input sentence was empty), it returns an empty string to handle this edge case gracefully.
  • Employs the max()function along with key=len to find the word in the words list with the maximum length.
  • Returns the longest_word