Define a Python function longestword that takes a string as

Define a Python function, longest_word(), that takes a string as its (only) argument. The function returns the longest word from inside the string. For example, calling longest_word(\"this is a very long sentence\") would return \"sentence\" (if two or more words tie for the longest, you may return either one).

Solution

def longest_word(s):
strings = s.split()
maxLength = 0
maxString = \"\"
for each in strings:
if maxLength < len(each):
maxLength = len(each)
maxString = each
return maxString;

  
print longest_word(\"this is a very long sentence\")
  

Output:

sh-4.3$ python main.py sentence   

Define a Python function, longest_word(), that takes a string as its (only) argument. The function returns the longest word from inside the string. For example,

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site