Python Program to Find Even Length Word

Python Program to Find Even Length Word
Reading Time: 9 minutes

Table of Contents

Python Program to Print Even-Length Words in a String: A Comprehensive Guide

Python is a versatile programming language that makes solving text-based problems a breeze. One such problem is finding and printing even-length words in a string. Whether you’re a beginner or an experienced programmer, this guide will walk you through everything you need to know about writing a Python program to print even-length words in a string. By the end of this article, you’ll not only understand how to solve this problem but also gain insights into optimizing and expanding your code for real-world applications.

What Are Even-Length Words?

Even-length words are words that contain an even number of characters. For example:

  • The word “Python” has 6 letters (even).
  • The word “is” has 2 letters (even).
  • The word “great” has 5 letters (odd).

Identifying even-length words is a common task in text processing, data analysis, and natural language processing (NLP). It’s also a great exercise for beginners to practice string manipulation, loops, and conditionals in Python.

Why Is This Problem Useful?

Finding even-length words might seem simple, but it has practical applications:

  1. Text Analysis: Identifying patterns in text data, such as the distribution of word lengths.
  2. Data Cleaning: Filtering out words of specific lengths during preprocessing.
  3. Word Games: Creating puzzles or challenges based on word lengths.
  4. NLP Tasks: Building features for machine learning models, such as sentiment analysis or text classification.

Step-by-Step Approach to Print Even-Length Words

Let’s break down the problem into simple steps:

Step 1: Splitting the Input String into Words

The first step is to split the input string into individual words. Python’s split() method is perfect for this. By default, split() divides a string into words based on spaces.

				
					sentence = "Python is a great language"
words = sentence.split()
print(words)  # Output: ['Python', 'is', 'a', 'great', 'language']
				
			

Step 2: Iterating Through the List of Words

Next, we’ll use a for loop to go through each word in the list.

				
					for word in words:
    print(word)
				
			

Step 3: Checking the Length of Each Word

To determine if a word has an even length, we’ll use the len() function and the modulus operator (%). If the length of the word divided by 2 leaves no remainder, it’s even.

				
					if len(word) % 2 == 0:
    print(word)
				
			

Step 4: Storing Even-Length Words

We’ll store the even-length words in a new list for easy access.

				
					even_length_words = []
for word in words:
    if len(word) % 2 == 0:
        even_length_words.append(word)
				
			

Step 5: Displaying the Result

Finally, we’ll print the list of even-length words.

				
					print(even_length_words)  # Output: ['Python', 'is', 'great', 'language']
				
			

Full Python Code to Print Even-Length Words

Here’s the complete program:

				
					def print_even_length_words(sentence):
    words = sentence.split()
    even_length_words = [word for word in words if len(word) % 2 == 0]
    return even_length_words

# Example usage
sentence = "Python is a great language"
print(print_even_length_words(sentence))  # Output: ['Python', 'is', 'great', 'language']
				
			

Alternative Methods to Solve the Problem

1. Using List Comprehension

List comprehension is a concise way to create lists in Python. Here’s how you can use it to find even-length words:

				
					even_length_words = [word for word in sentence.split() if len(word) % 2 == 0]
				
			

2. Using the filter() Function

The filter() function can be used with a lambda function to filter even-length words:

				
					even_length_words = list(filter(lambda word: len(word) % 2 == 0, sentence.split()))
				
			

3. Using Regular Expressions

Regular expressions (re module) can also solve this problem:

				
					import re
even_length_words = re.findall(r'\b\w{2,4,6,...}\b', sentence)
				
			

Common Mistakes to Avoid

  1. Forgetting to Split the String: Always use split() to break the string into words.

  2. Misusing len(): Ensure you’re applying len() to individual words, not the entire string.

  3. Overcomplicating the Solution: Stick to simple loops and conditionals unless necessary.

Optimizing the Program

To make the program more robust:

  • Handle edge cases like empty strings or strings with no even-length words.

  • Remove punctuation using string.punctuation or re.sub().

				
					import string

def clean_sentence(sentence):
    return sentence.translate(str.maketrans('', '', string.punctuation))

sentence = "Python, is a great language!"
cleaned_sentence = clean_sentence(sentence)
print(print_even_length_words(cleaned_sentence))  # Output: ['Python', 'is', 'great', 'language']
				
			

Testing Your Program

Always test your code with different inputs:

  • Input"Hello world" → Output['Hello', 'world']

  • Input"I love coding in Python" → Output['love', 'in', 'Python']

  • Input"No even words here" → Output[]

Use Python’s assert statement for automated testing:

				
					assert print_even_length_words("Hello world") == ['Hello', 'world']
				
			

Expanding the Program’s Functionality

You can modify the program to:

  • Find odd-length words.

  • Count the number of even-length words.

  • Find the longest even-length word.

				
					# Find the longest even-length word
longest_even_word = max(even_length_words, key=len)
print(longest_even_word)  # Output: 'Python'
				
			

Practical Applications

  • Text Analysis: Analyzing word length distributions in large datasets.

  • NLP: Preprocessing text for machine learning models.

  • Word Games: Creating puzzles or challenges based on word lengths.

Conclusion

Writing a Python program to print even-length words in a string is a great way to practice string manipulation and problem-solving in Python. By following this guide, you’ve learned how to:

  • Split strings into words.

  • Use loops and conditionals to filter words.

  • Optimize and expand your program for real-world use.

Related Courses

Join SystechGroup’s course today and upgrade your skills. Enroll now!

TrichyCoimbatore

FAQs

The program has a time complexity of O(n), where n is the number of words in the string.

Yes, using split() without arguments handles extra spaces and tabs.

Use string.punctuation or re.sub() to clean the input.

Convert the string to lowercase using str.lower().

Yes, but consider processing the file line by line to save memory.