Last modified: Jun 26, 2023 By Alexander Williams
Python: Find Shortest or Longest Word in String
In this article, we'll learn how to find the longest or the shortest word in a string.
Find the longest word in a string
Here are the steps to get the longest word in a string:
- Split the string into a list by space using the split() method.
- Initialize a variable to store the longest word.
- Iterate over each word in the list.
- Compare each word's length with the length of the current longest word.
Here is an example:
sentence = "The quick brown fox jumps over the lazy dog"
words = sentence.split() # Split the string into a list of words
longest_word = '' # Variable to store the longest word
# Iterate over each word and compare lengths to find the longest word
for word in words:
if len(word) > len(longest_word):
longest_word = word
print("Longest word:", longest_word) # Print the longest word
Output:
jumps
Find the shortest word in a string
Follow these steps to find the shortest word in a string:
- Split the string into a list by space using the
split()
method. - Initialize a variable to store the shortest word.
- Set the initial shortest word to be the first word in the list.
- Iterate over each word in the list and compare its length with the length of the current shortest word.
Let's see an example.
sentence = "The quick brown fox jumps over the lazy dog"
words = sentence.split() # Split the string into a list of words
shortest_word = words[0] # Initialize shortest_word with the first word in the list
# Iterate over each word and compare lengths to find the shortest word
for word in words:
if len(word) < len(shortest_word):
shortest_word = word
print("Shortest word:", shortest_word) # Print the shortest word
Output:
Shortest word: The
As you can see, "the" is the shortest word in the list.
Conclusion
Python offers straightforward procedures for detecting a string's shortest and longest words.
Throughout this tutorial, we used the split method to find the shortest and longest words in a given string.