Write a program in python to read string and print longest word and its position

In this tutorial we first read the input string from user, and find the longest word and its position. To perform this task we follow the below steps-

  1. Read the String from user.
  2. Apply String split() method to split the string into a list of constituent words.
  3. Find the longest word in the list using max(List, key=len)
  4. Find the position/ index of longest word using String.index().
  5. Print the longest word and it's position

Example (Easy Approach)

In the program below, we read a string from user and find the longest word and it's position in the string.

# Python program to read a String and Print Longest
# word and it's Position
# Read input string
str = input("Enter a String: ")
# Split the string to a list of words
word_list = str.split()
# Find the longest word
longest_word = max(word_list, key = len)
# Find the position (index) of longest word
pos = str.index(longest_word)
# Print the longest word and it's position
print("Longest word: ",longest_word)
print("Position of Longest word: ", pos)

Output

Enter a String: Binary Study Python programming made easy
Longest word: programming
Position of Longest word: 20

Program Explanation

We read the string from user using input() function. Assign the input string to str.

Then we create a list of words word_list using String split() method. The output of this method is a list. The string is split by the space.

Now we find max(word_list, key = len) function. It returns the longest element based on the length. Assign this to longest_word.

Now we apply String index() method passing longest_word as an argument. It returns the index of the first character of the longest_word. It is our desired position (pos)of the longest word in the string. We could apply String find() method. It also returns the index of the first character of the passed sub string as parameter.

Finally print the longest word and it's position. 

Example (Using for Loop):

In the program below, the approach is same as the above. The only difference, we used for loop to find the longest words instead of using max() method.

str = input("Enter a String:")
words = str.split()
longest_word = words[0
max_len = len(words[0])
for index, word in enumerate(words):
    if len(word)> max_len:
        max_len = len(word)
        longest_word = word
    else:
        pass
idx = str.find(longest_word) # idx = str.index(longest_word)
print("Longest word: ",longest_word)
print("Position of Longest word: ", idx)

Output

Enter a String: Binary Study Python programming made easy
Longest word:  programming
Position of Longest word: 20

Notice the output of the two programs are the same. The second program is more naive in approach.

Methods and Functions Used

The following methods and functions are used in above two programs:

The input() Function

input(str)

Here str is a string to show a default message before input.

It returns a string with value entered. 

The String split() Method

str.split(separator, maxsplit)

Here separator specifies the separator to used, default is white space. The maxsplit specifies the number of split to do. Both the parameters are optional.

It returns a list. The words separated by white space are the list items.

>>> "Binary study programming made easy".split()
['Binary', 'study', 'programming', 'made', 'easy']

The max() Function

max(iterable, key = len)

Here iterable can be any data type that is iterable such as list, tuple, dictionary, etc. The key is used to make comparison on that basis it returns the value. Here we used length (len) the basis of comparison.
It returns the word of maximum length.

>>> max(['Binary', 'study', 'programming', 'made', 'easy'], key = len)

'programming'

The String index() Method

str.index(substr)

Here substr is value to search for. As in our example substr is an individual word (longest_word).

It returns the index of first occurrence of the value of substr.

>>> "Binary study programming made easy".index('programming')
13

The len() Function

len(object)

Here object is a sequence or collection. A string is a sequence of characters.

It returns the number of items in the object. (It returns number of characters.)

>>> len('programming') 11

The String find() Method

str.find(substr)

Same as the string index() method. The only difference is that it returns -1 if the match is not successful while the index() method throws an exception.

>>> "Binary study programming made easy".find('programming') 13


You may be interest in the following articles-

Comments