Exercise 44
Write a python program as function which groups in a list all the words which begin with a capital letter in a given string s.
Example for s = "Python is a high level programming language. Originally developed by Guido van Rossum in 1989." The program should return the list: ["Python", "Originally", "Guido", "Rossum"]
Solution
def extract_capitalized_words(s): words = s.split() # split the string into words capitalized_words = [] for word in words: if word[0].isupper(): # check if the first character of the word is uppercase capitalized_words.append(word) return capitalized_words # Example usage s = "Python is a high level programming language. Originally developed by Guido van Rossum in 1989." capitalized_words = extract_capitalized_words(s) print(capitalized_words) """ Output: ['Python', 'Originally', 'Guido', 'Rossum'] """
In this program:
- We use tsplit() method: to convert the string s into words using.
- And then iterates: over each word in the list of words and checks if the first character of the word is uppercase using the isupper() method.
- If the first character of the word is uppercase: we add the word to the list
- Finally: the program returns the list of capitalized words.
Younes Derfoufi
my-courses.net
[…] Exercise 41 || Solution […]