Exercise 46

Write a Python algorithm as a function which takes as parameter a string s and which returns the list of all the words contained in s whose length is greater than or equal to 8. Example if s = 'Python is oriented programming language. Python is the most used programming language'. The function returns the words list :

['oriented', 'programming', 'language', 'programming', 'language']

Solution

def find_long_words(s):
    words = s.split()  # split the string into a list of words
    long_words = [w for w in words if len(w) >= 8]  # use a list comprehension to filter for long words
    return long_words

s = 'Python is oriented programming language. Python is the most used programming language'
result = find_long_words(s)
print(result)
# output: ['oriented', 'programming', 'language.', 'programming', 'language']





Note that the last word "language." has a length of 9, which is greater than or equal to 8, so it is also included in the list. If you want to exclude punctuation marks like the period at the end of "language.", you can modify the function to remove them using the strip() method or a regular expression.

 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 46: python program to extract all word of given length”

Leave a Reply