Python - Find words greater than given length

PythonServer Side ProgrammingProgramming

When it is required to find words that are greater than a specific length, a method is defined that splits the string, and iterates through it. It checks the length of the word and compares it with the given length. If they match, it is returned as output.

Example

Below is a demonstration of the same

def string_check(string_length, my_string):
   result_string = []
   words = my_string.split(" ")
   for x in words:
      if len(x) > string_length:
         result_string.append(x)
   return result_string
string_length = 3
my_string ="Python is always fun to learn"

print("The string is :")
print(my_string)
print "\nThe words in the string with length greater than" , string_length , "is :"
print(string_check(string_length, my_string))

Output

The string is :
Python is always fun to learn

The words in the string with length greater than 3 is :
['Python', 'always', 'learn']

Explanation

  • A method named ‘string_check’ is defined that takes the string, and its length as parameter.

  • An empty list is defined.

  • The string is split based on spaces, and assigned to a variable.

  • This variable is iterated over, and the given length and the length of the each word is checked.

  • If the length of the word is greater than the length of the string, it is appended to the empty string.

  • It is returned as output.

  • Outside the function, a string length is defined, and a string is defined.

  • This string is displayed on the console.

  • The method is called and the output is displayed on the console.

raja
Published on 20-Sep-2021 10:45:23
Advertisements