Home >>Python Programs >Capitalizes the first letter of each word in a string in Python
In this example, we will see a Python program through which we can convert the first letter of each word of a given string in to a capital letter
We can either use the title() method or we can use the loop and the split() method to convert the first letter of each word in to a capital letter.
Program 1:
# python program to capitalizes the
# first letter of each word in a string
# function
def capitalize(text):
return text.title()
# main code
str1 = "Hello world!"
str2 = "hello world!"
str3 = "HELLO WORLD!"
# printing
print("str1: ", str1)
print("str2: ", str2)
print("str3: ", str3)
print()
print("capitalize(str1): ", capitalize(str1))
print("capitalize(str2): ", capitalize(str2))
print("capitalize(str3): ", capitalize(str3))
# python program to capitalizes the
# first letter of each word in a string
# function
def capitalize(text):
return ' '.join(word[0].upper() + word[1:] for word in text.split())
# main code
str1 = "Hello world!"
str2 = "hello world!"
str3 = "HELLO WORLD!"
# printing
print("str1: ", str1)
print("str2: ", str2)
print("str3: ", str3)
print()
print("capitalize(str1): ", capitalize(str1))
print("capitalize(str2): ", capitalize(str2))
print("capitalize(str3): ", capitalize(str3))