PUBLISHED ON: JULY 2, 2021
Python program to print even length words in a string
In this tutorial, you will learn to print even-length words in a given string. Strings in Python are a sequence of characters wrapped inside single, double, or triple quotes. To solve this problem, we will have to find the length of the words and select only those words whose length is even. For example,
Input: "Welcome to Studytonight"
Output: to Studytonight
Input: "hello to the coders"
Output: to coders
The approach for solving this problem is to use the split() method to separate out the words in the string. It is a function of string class that returns a list of the words in the string. Then we will use the len() method to find the length of the words returned by split(). We will use the if condition to select and print only those words whose length is even.
Algorithm
Follow the algorithm to understand the approach better.
Step 1- Define a function that will print even words in the string
Step 2- Use split to extract the words
Step 3- Run a loop to iterate over the words
Step 4- Check if the length is even
Step 5- Print word if the length is even
Python Program
Look at the program to understand the implementation of the above-mentioned approach.
Words in a string can be extracted by giving space (" ") as the separator.
To check if the word has an even length we will divide the length by 2 and see if the remainder is 0 or not. If the remainder is 0, this means that the length is even and then we will print the word.
# print even length words
# function
def PrintEvenWords(s):
# splitting words
s=s.split(' ')
# iterate over words
for word in s:
if len(word)%2==0:
# printing even length words
print(word)
string= " Python is good for me"
PrintEvenWords(string)
Python
is
good
me
Conclusion
In this approach, we have discussed how to print words with even length in a string using split() and len() built-in functions.