Python program to accept a string find the longest word and its length

 

Python program to accept a string find the longest word and its length

Write a Python program to accept a string from the user and display the longest word of that sentence along with its length.

Video Tutorial

Steps:

1. Read the input string from the user using the input function and store it in a string variable.

2. Pass the input string to longestWordLength method which finds the longest word and its length. The returned values are stored in w and l respectively.

3. Initialize the length of the longest word to 0  and  Initlize w (longest word) to empty

4. Split the string into words using the splits function.

5. Compare the length of each word against the length. If the length of the word is more than the length, replace the length value with the length of the new word and w with the new word.

6. Finally return the longest word and its length.

7. Display the longest word and its length in the called function.

Source code of Python program to accept a string find the longest word and its length

# Write a Python program to accept a string from the user 
# and display the longest word of that sentence along with its length
  
def longestWordLength(string):  
    length = 0   # Initilize length to 0
    w = ''       # Initlize word to empty
      
    # Finding longest word in the given sentence and word
    for word in string.split(): 
        if(len(word) > length): 
            length = len(word) 
            w = word
    return (length, w)  
  
string = input("Enter the string: ")
l, w = longestWordLength(string)
print("Longest word is ", w, " and its length is ", l)

Output:

Enter the string: VTUPulse A Computer Science and Engineering Portal

Longest word is Engineering and its length is 11

Summary:

This tutorial discusses how to write a Python program to accept a string find the longest word and its length. If you like the tutorial share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *

Welcome to VTUPulse.com


Computer Graphics and Image Processing Mini Projects -> Click Here

Download Final Year Project -> Click Here

This will close in 12 seconds