Python Capitalize First Letter of Each Word

How to capitalize the first letter of each word in string?

In Python, to capitalize (to uppercase) first character of each word in a continuous string you can use capitalize() or title() method on that string.

capitalize() Example

However if you want to uppercase only the first letter of the whole string you can use capitalize() method on the string. If first letter of string is already in uppercase it capitalize method returns the original string.
# Python program to demonstrate the use of capitalize() function

myString = "i am learning python"
myString = myString.capitalize()
print(myString)

''' Output of above code:-

I am learning python

'''

title() Example

If have a string "i am learning python" then the example below capitalizes it.
# Python program to demonstrate the use of title() function

myString = "i am learning python"
myString = myString.title()
print(myString)

''' Output of above code:-

I Am Learning Python

'''

Python program to capitalize first and last letter of each word in a string

def capitalize_first_and_last_char(string1):
     
	string1 = string1.title()
     
	output_string =  ""

	wordList = string1.split()

	for word in wordList:
		output_string += word[:-1] + word[-1].upper() + " "

	return output_string[:-1]  
     
print(capitalize_first_and_last_char("I am learning python"))
print(capitalize_first_and_last_char("on www.computerscienceai.com"))

''' Output of above code:-

I AM LearninG PythoN
ON Www.Computerscienceai.CoM

'''