Find the longest word from string in python

275 viewsPython

Find the longest word from string in python

Have the function LongestWord(sen) take the sen parameter being passed and return the longest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty. Words may also contain numbers, for example “Hello world123 567”

Farjanul Answered question July 22, 2022
0

import re
def LongestWord(sen):
  lst = sen.split()
   longest_word = ''
  for word in lst:
    pureWord = re.sub(r"[^a-zA-Z0-9]", "", word)
    if len(pureWord) > len(longest_word):
        longest_word = pureWord
   return longest_word
 # keep this function call here 
print(LongestWord(input()))

Farjanul Answered question July 22, 2022
0