Exercise 38
Write a Python program that takes as input a string of characters 's' and returns the longest word found in 's'.
Solution
def longest_word(s): # Split string into words words = s.split() # Initialize variables to store longest word and its length longest = '' longest_len = 0 # Iterate through words in list for word in words: # Check if current word is longer than current longest word if len(word) > longest_len: longest = word longest_len = len(word) return longest # Example usage s = "Python is the most popular programming language!" longest = longest_word(s) print(longest) # output: 'programming'
Younes Derfoufi
my-courses.net