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-
- Read the String from user.
- Apply String split() method to split the string into a list of constituent words.
- Find the longest word in the list using max(List, key=len).
- Find the position/ index of longest word using String.index().
- 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 stringstr = input("Enter a String: ")# Split the string to a list of wordsword_list = str.split()# Find the longest wordlongest_word = max(word_list, key = len)# Find the position (index) of longest wordpos = str.index(longest_word)# Print the longest word and it's positionprint("Longest word: ",longest_word)print("Position of Longest word: ", pos)
Output
Enter a String: Binary Study Python programming made easyLongest word: programmingPosition 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 = wordelse:passidx = 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 easyLongest word: programmingPosition 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)
>>> 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-
Further Reading:
- How to Load and Visualize Multiple Images in Python
- Mathematical Operations On Images Using OpenCV and NumPy in Python
- Basic Operations on Images using OpenCV in Python
- Different ways to load images in Python
- How to compute mean, standard deviation, and variance of a tensor in PyTorch
- How to calculate mean and standard deviation of images in PyTorch
- How to normalize image dataset in PyTorch
Useful Resources:
Comments
Post a Comment