Exercise 39

Write a Python algorithm that takes a string characters 's' as input and return the number of words contained in this string 's'.


def count_words(s):
    # Split string into words
    words = s.split()

    # Count the number of words and return the result
    return len(words)

# Example usage
s = "Python is an object oriented, high level programming language"
num_words = count_words(s)
print(num_words) # output: 9


Younes Derfoufi

One thought on “Soultion Exercise 39: python algorithm to the number of words in a given string”

Leave a Reply