Exercise 22

Write a simple program in Python that returns the first word of a given text. Example for the text: T = ‘Python is a wonderful programming language’, the program must return Python


def first_word(text):
    # split the text by whitespace
    words = text.split()
    # return the first word
    return words[0]
# Example usage
T = 'Python is a wonderful programming language'
print(first_word(t)) # output: 'Python'

In this program:

  1. We defines a function called first_word: that takes a single argument, text.
  2. The splits() method: is used to convert the text T into a list of words
  3. We then returns the first word: in the list (which is at index 0).

The example usage at the bottom of the program demonstrates how to call the function on the given text and print the result.

Younes Derfoufi

One thought on “Solution Exercise 22: python algorithm that extract the first word in given text”

Leave a Reply