Signup/Sign In

Program To Find words that are greater than the given length k

In this tutorial, we will learn to find words in a string that are greater than the given length k in Python. Strings in Python are a sequence of characters wrapped inside single, double, or triple quotes. A word can be defined as a substring separated by space that exists in the string. Each word in the string has some length, we have to print only those words whose length is larger than a given length k. For example,

Input: "hello welcome to studytonight", k=6

Output: welcome studytonight

Input: " Python tutorial for beginners", k=7

Output: tutorial beginners

To solve this problem, we will have to first separate the words in the string and then check each word for its length. If the length is greater than a given value k, the word will be printed else, we will move on to the next word.

To execute this approach in Python, we will use some built-in functions of the string class.

To get words from the string, we will use the split() method. It accepts a string and the separator as parameters and breaks the string at places wherever the separator is found in the string.

To get the length of the string or the substring, we will use the len() method. This method returns the size of a string.

Let's see the algorithm to understand the working of the program.

Algorithm

Follow the algorithm to understand the approach better.

Step 1- Define a function that will find words with length greater than 'k'

Step 2- To get words from the string, split the string wherever space comes

Step 3- Run a loop to check words in the string

Step 4- If the length of the word is greater than a given value k

Step 5- Print the word

Step 6- Else, move on to the next iteration

Step 7- Declare a string and value of k

Step 8- Call function and give string and k as parameters

Python Program

Look at the program to understand the implementation of the above-mentioned approach. To get words from the string, we will give space (" ") as a parameter in the split() function that will break the sentence based on the space.

def word_k(k, s):    
    # split the string where space comes
    word = s.split(" ")
    # iterate the loop for every word
    for x in word:
        # if length of current word
        if len(x)>k:
          # greater than k then
          print(x)
k = 3
s ="Python is good"
word_k(k, s)


Python
good

Conclusion

In this tutorial, we have seen how to find and print those words which have a length greater than a given length k. We have used built-in functions of the string class in our program to find the length of a word.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.