# Python program to print even length words in a string

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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.

## Approach

• 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.

## str.split()

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()

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.


### Example

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)


### Output

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.

### Syntax

evenWords = filter(lambda x: len(x) % 2 == 0, 'this is a test string'.split())


### Example

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')


### Output

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.

### Using Lambda

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)


### Output

this
is
test
string


#### Note

When using split() function with multiple statements that end with a period (.), it is also counted along with the last word.

### Example

x = 'Example statement 1. Some line 2.'


When passing the above string to the function it will also include “1.” and “2.”.

### Output

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('.', '')


### Example

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)


### Output

Some
line


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.

## Regex Pattern

### Example

\w\.(\s[A-Z])?


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.

Updated on 13-Oct-2022 11:58:05