Question 3 of 6intermediate🔧 ApplyLong Answer4 marks

Write a user defined function to convert a string with more than one word into title case string where string is passed as parameter. (Title case means that the first letter of each word is capitalised)

Correct Answer

python def titleCase(string): """Function to convert a string to title case""" words = string.split(' ') title_string = '' for word in words: if len(word) > 0: # Convert first character to uppercase and append rest of word title_string = title_string + word[0].upper() + word[1:] + ' ' return title_string.strip()

Example usage

text = input("Enter a string: ") print("Original string:", text) print("Title case string:", titleCase(text))

Output:

Enter a string: hello world Original string: hello world Title case string: Hello World

Exercise: PROGRAMMING PROBLEMS | Q: 2 | (Page 14)
For More Understanding

Explanation

The solution uses the split(' ') method shown in the NOTES section to break the string into individual words. The upper() method from the table is used to convert the first character of each word to uppercase. String indexing (as demonstrated in Program 8-3) is used to access individual characters. The function iterates through each word, capitalizes the first letter, and concatenates it with the remaining characters of the word. Finally, all words are joined back with spaces to form the title case string.

Solution Steps

  1. Step 1: Define function titleCase() that takes string as parameter

  2. Step 2: Split the string into words using split(' ') method

  3. Step 3: Initialize empty string title_string to store result

  4. Step 4: Loop through each word and convert first character to uppercase using upper()

  5. Step 5: Concatenate capitalized first letter with remaining characters of each word

  6. Step 6: Return the final title case string after removing trailing spaces