Python program to find the smallest word in a sentence


Welcome to this in-depth tutorial on how to write a Python program to find the smallest word in a sentence. Whether you are a beginner or an intermediate Python programmer, this guide will offer the knowledge and skills necessary to use Python's powerful features in text manipulation.

Problem Statement

Given a sentence, our task is to find the smallest word. The "smallest" word refers to the word with the fewest characters. In case of a tie, we'll return the first occurring smallest word.

Approach

We start by splitting the sentence into words, which we'll accomplish by using spaces as the delimiters. As we traverse through each word, we'll keep track of the smallest word found so far. By the end of the sentence, we'll have identified the smallest word.

Example

Here is the C++ code that solves this problem −

def find_smallest_word(sentence):
   # Split the sentence into words
   words = sentence.split()
   
   # Find the smallest word
   smallest_word = min(words, key=len)
   
   return smallest_word

# Test the function
sentence = "Python programming is fun and rewarding"
print(f"The smallest word in the sentence is '{find_smallest_word(sentence)}'")

Output

The smallest word in the sentence is 'is'

This program takes a sentence as input and outputs the smallest word in the sentence.

In this program, we define a function find_smallest_word() that takes a sentence as input. The split() method is used to break the sentence into a list of words. Then, the min() function, along with a key parameter set to Python’s built-in len function, is used to find the smallest word based on its length. Finally, we test the function with a sample sentence.

Delving Deeper: Python Text Manipulation

Python offers a rich set of features for text manipulation. Functions like len(), split(), and min() are just the tip of the iceberg. With Python, you can perform complex text manipulations, such as pattern matching using regular expressions, text cleaning, and more. It's worthwhile to explore these features as they are widely used in areas like data analysis, natural language processing, and web scraping.

Conclusion

In this tutorial, we've learned how to write a Python program to find the smallest word in a sentence. We've seen how Python's built-in functions can be effectively used to perform text manipulation tasks.

Updated on: 18-May-2023

306 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements