Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - Find words greater than given length
When it is required to find words that are greater than a specific length, we can define a method that splits the string and iterates through it. It checks the length of each word and compares it with the given length. If the word length is greater, it is added to the result.
Using a Custom Function
Below is a demonstration using a custom function ?
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))
The string is : Python is always fun to learn The words in the string with length greater than 3 is : ['Python', 'always', 'learn']
Using List Comprehension
A more concise approach using list comprehension ?
my_string = "Python is always fun to learn"
min_length = 4
words = my_string.split()
result = [word for word in words if len(word) > min_length]
print("Original string:", my_string)
print(f"Words longer than {min_length} characters:", result)
Original string: Python is always fun to learn Words longer than 4 characters: ['Python', 'always', 'learn']
Using Filter Function
Using the built-in filter() function with a lambda ?
my_string = "Python programming is really amazing"
min_length = 5
words = my_string.split()
result = list(filter(lambda word: len(word) > min_length, words))
print("Original string:", my_string)
print(f"Words longer than {min_length} characters:", result)
Original string: Python programming is really amazing Words longer than 5 characters: ['Python', 'programming', 'really', 'amazing']
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Custom Function | Good | Standard | Complex logic |
| List Comprehension | Excellent | Fast | Simple filtering |
| Filter Function | Good | Fast | Functional programming |
Conclusion
List comprehension provides the most readable and efficient solution for filtering words by length. Use custom functions when you need additional processing logic beyond simple filtering.
Advertisements
