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)
Question
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)
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
Here's a user-defined function that converts a string with more than one word into title case:
def to_title_case(string):
# Split the string into words
words = string.split()
# Capitalize the first letter of each word
title_case_words = [word.capitalize() for word in words]
# Join the words back into a single string
title_case_string = ' '.join(title_case_words)
return title_case_string
# Example usage
input_str = "hello world, this is a test"
title_case_str = to_title_case(input_str)
print("Original String:", input_str)
print("Title Case String:", title_case_str)
Output:
Original String: hello world, this is a test
Title Case String: Hello World, This Is A Test
Explanation:
The function uses the
split()
method to break the string into words.It then uses a list comprehension to capitalize the first letter of each word using the
capitalize()
method.Finally, it uses the
join()
method to combine the words back into a single string with spaces between them.
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month