Skip to content
Related Articles

Related Articles

Python program to print even length words in a string

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 03 Aug, 2022

Given a string. The task is to print all words with even length in the given string.

Examples: 

Input: s = "This is a python language"
Output: This
              is
              python
              language
Input: s = "i am laxmi"
Output:     am

Method: Finding even length words using for loop and if statement and without using the def function. First split the given string using the split() function and then iterate the words of a string using for loop. Calculate the length of each word using the len() function. If the length is even, then print the word.

Python3




# Python code
# To print even length words in string
 
#input string
n="This is a python language"
#splitting the words in a given string
s=n.split(" ")
for i in s:
  #checking the length of words
  if len(i)%2==0:
    print(i)
 
# this code is contributed by gangarajula laxmi


Output

This
is
python
language

Approach: Split the string using split() function. Iterate in the words of a string using for loop. Calculate the length of the word using len() function. If the length is even, then print the word. Below is the Python implementation of the above approach: 

Python3




# Python3 program to print
# even length words in a string
 
def printWords(s):
     
    # split the string
    s = s.split(' ')
     
    # iterate in words of string
    for word in s:
         
        # if length is even
        if len(word)%2==0:
            print(word)
 
 
# Driver Code
s = "i am muskan"
printWords(s)


Output

am
muskan

Method: Using the lambda function

Python3




# Python code
# To print even length words in string
 
#input string
n="geeks for geek"
#splitting the words in a given string
s=n.split(" ")
l=list(filter(lambda x: (len(x)%2==0),s))
print(l)


Output

['geek']

Method: Using list comprehension

Python3




# python code to print even length words
 
n="geeks for geek"
s=n.split(" ")
print([x for x in s if len(x)%2==0])


Output

['geek']

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!