Python program to print even length words in a string
Given a string, the task is to print only the words whose lengths are even. For example, given "Python is great", the even-length words are "Python" and "is", since their lengths (6 and 2) are divisible by 2. Let’s explore multiple methods to extract even-length words from a string in Python.
Using list comprehension
This method splits the string into words, filters out even-length words using list comprehension and joins them into a single output string. It is the fastest and cleanest approach, as it avoids multiple print calls and unnecessary loops.
s = "This is a python language"
wrds = s.split()
even_wrds = [w for w in wrds if len(w) % 2 == 0]
res = " ".join(even_wrds)
print(res)
Output
This is python language
Explanation:
- s.split() splits the string into a list of words.
- [w for w in wrds if len(w) % 2 == 0] filters words with even length.
- " ".join(even_wrds) combines the filtered words into a space-separated string.
Using filter() with Lambda
This approach uses filter() to extract even-length words and lambda to define the condition, making it a functional programming alternative. The join() function combines the words into a single output.
s = "Python is great"
wrds = s.split()
even_wrds = filter(lambda w: len(w) % 2 == 0, wrds)
res = " ".join(even_wrds)
print(res)
Output
Python is
Explanation:
- filter(lambda w: len(w) % 2 == 0, wrds) selects words where length is divisible by 2.
- " ".join(even_wrds) converts the filtered words into a string.
Using Generator Expression
A memory-efficient approach, this method generates words dynamically instead of storing them in a list. It filters even-length words on the fly using a generator expression and then joins them efficiently.
a = "geeks for geek"
wrds = a.split()
even_wrds = (w for w in wrds if len(w) % 2 == 0)
res = " ".join(even_wrds)
print(res)
Output
geek
Explanation:
- (w for w in wrds if len(w) % 2 == 0) dynamically generates words of even length.
- " ".join(...) combines them into the output string.
Using itertools.compress()
This method creates a boolean mask to identify even-length words and uses itertools.compress() to efficiently select only those words. It is memory-efficient and ideal for large strings.
from itertools import compress
s = "Python is fun language"
words = s.split()
selectors = [len(w) % 2 == 0 for w in words]
res = " ".join(compress(words, selectors))
print(res)
Output
Python is language
Explanation:
- [len(w) % 2 == 0 for w in words] creates a boolean mask where True corresponds to even-length words.
- compress(words, selectors) yields only the words selected by True in the mask.
- " ".join(...) concatenates them into a string.