- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to print even length words in a string
In Python Programming Language, Length is the concept of calculating the entire range of the string that begins from the first character of the string till the last character of the string. Printing and calculating even length in a string is a basic exercise in the programing language.
In this tutorial, we will learn about the solution and approach to find out all words in a string having even length. A number is considered odd if it divides by 2 evenly, i.e. leaving no remainder. This property should hold for the length of the words we need. So the objective of the program is to print only the words that has even length of words and skip all those words which do not satisfy the above mentioned property.
For example, if we have a string of words “A big cube was found inside the box.“, for this string our program should only print the words : “cube” and “inside” as the respective length of these words are 4 and 6.
Split the string into words, using str.split() function.
Iterate through the words.
Calculate length of word using len() function.
If length is even, print the word.
Otherwise do nothing.
This is the built-in function applicable for strings in python. The use of this function is to split a string function according to a separator specified or a space if no separator is specified.
The help in Python interpreter for the following function returns this information below −
split(self, /, sep=None, maxsplit=-1) Return a list of the words in the string, using ‘sep’ as the delimiter string. sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit.
Len is most commonly used function of python that is used to count the number of characters or elements in any data object of python. For example for the string “aaa” len(“aaa”) will return 3.
From the built-in help in Python interpreter −
len(obj, /) Return the number of items in a container. For a string, its wrapper str.__len__() is called.
In the example below, we have implemented the above approach. We have created a function to filter out all the words having even length from a string.
def printEvenLengthWords(s): # splitting the words in a given string words = s.split() # same as s.split(' ') for word in words: # checking the length of words if len(word) % 2 == 0: print(word) # input string sample = 'this is a test string' # calling the function printEvenLengthWords(sample)
this is test string
A little Python Bonus
Python contains a built-in function called filter(), which returns an iterator.
It takes two arguments, first is a Boolean function, second is the iterable on which it should be applied. We can use any of the above methods as a function for this.
Special care must be taken where using filter() as it is exhaustible, meaning once it is used, either for traversal or for conversion to list, it will return None if traversed again, so it’s better to convert it to a list and store in another variable.
evenWords = filter(lambda x: len(x) % 2 == 0, 'this is a test string'.split())
def printEvenLengthWords(s): # splitting the words in a given string words = s.split() # same as s.split(' ') # checking the length of words evenWords = filter(lambda x: len(x) % 2 == 0, words) for word in evenWords: print(word) # calling the function with input string passed in directly printEvenLengthWords('this is a test string')
this is test string
In the above example, the argument of lambda function ‘x’ takes place of every element returned by split function. It works a lot like for loop, but is shorthand python way.
Python One Liner using filter() and list comprehension
We can directly call print() on the filter object with an optional parameter ‘sep’ set as ‘
’ or newline character. The ‘*’ at the beginning means unpack the iterable and print all of them, and the separator prints them in new lines. It can be done as follows.
def printEvenLengthWords(s): # please note that one liners are hard to understand # and may be frowned upon in some cases print(*filter(lambda x: len(x) % 2 == 0, s.split()), sep='
Using List Comprehension
def printEvenLengthWords(s): print(*[x for x in s.split() if len(x) % 2 == 0], sep='
') # input string sample = 'this is a test string' # calling the function printEvenLengthWords(sample)
this is test string
When using split() function with multiple statements that end with a period (.), it is also counted along with the last word.
x = 'Example statement 1. Some line 2.'
When passing the above string to the function it will also include “1.” and “2.”.
1. Some line 2.
It can be fixed by a simple hack. We can remove all periods with a replace() call as follows −
x = 'Example statement 1. Some line 2.' x = x.replace('.', '')
def printEvenLengthWords(s): # handle full stops s = s.replace('.', '') # splitting the words in a given string words = s.split() # same as s.split(' ') for word in words: # checking the length of words if len(word) % 2 == 0: print(word) # input string sample = 'Example statement 1. Some line 2.' # calling the function printEvenLengthWords(sample)
It should be noted however that it will remove periods even in the middle of sentences, for a more robust alternative, regex pattern can be used.
This checks whether any word character is followed by a full stop and then either string terminates or a new sentence starts with a capital letter. Regex can be learned more in depth in other tutorials.
- Java Program to Print even length words
- Python program to print even numbers in a list
- Java Program to Print all unique words of a String
- Python program to print all even numbers in a range
- Python program to Count words in a given string?
- Check if a string contains a palindromic sub-string of even length in Python
- Python program to print Possible Words using given characters
- Print Words Vertically in Python
- C++ program to print unique words in a file
- Print all funny words in a string in C++
- Program to find maximum length of non-sharing words in Python
- C# program to Reverse words in a string
- Program to find length of longest path with even sum in Python
- Java Program to Print a String