Write a function, lenWords(STRING), that takes a string as an argument and returns a tuple containing length of each word of a string.
For example, if the string is "Come let us have some fun", the tuple will have (4, 3, 2, 4, 4, 3)
Answer by student
Detailed answer by teachoo
The question asks us to write a function, lenWords(STRING), that takes a string as an argument and returns a tuple containing the length of each word of a string. The function should perform the following steps:
- Split the string into a list of words using space as a separator. The split() method returns a list of strings after breaking the given string by the specified separator.
- Create an empty list to store the lengths of words . A list is a collection of items that can be changed or modified. We can create an empty list using square brackets [ ].
- Loop through each word in the list using a for loop . A for loop is used to iterate over a sequence, such as a list, tuple, or string.
- Get the length of the word using len() function. The len() function returns the number of items in an object, such as a list, tuple, or string.
- Append the length to the lengths list. The append() method adds an item to the end of the list.
- Convert the lengths list into a tuple using tuple() function . A tuple is a collection of items that cannot be changed or modified. The tuple() function creates a tuple from an iterable object, such as a list, set, or string.
- Return the result tuple using return statement. The return statement exits a function and returns a value to the caller.
The final code for the function is as follows: