Exercise 70

Write a python program as function which extract from a given string s , the list of all words whose len is less than or equal to 4. Example: if s = "The Python programming language is open source and very easy to learn" , the program must returns the list: L = ['The', 'is', 'open', 'and', 'very', 'easy', 'to'].

Solution

# define a function that takes a string s as input and returns a list of all words in s whose length is less than or equal to 4.
def extract_short_words(s):

    # at first we splits the input string s into a list of words using the split() method
    words = s.split()
    short_words = [word for word in words if len(word) <= 4] # filter the words with len <= 4
    return short_words

# Example of use of this program:
s = "The Python programming language is open source and very easy to learn"
short_words = extract_short_words(s)
print(short_words) # Output: ['The', 'is', 'open', 'and', 'very', 'easy', 'to']




 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 70: Python program that extracts all words from a given string s whose length is less than to 4”

Leave a Reply