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'.

Solution

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
my-courses.net

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

Leave a Reply