Python Program to Capitalize the First Letter of Each Word
Beginner · Strings
This program changes the first letter of every word in a sentence to a capital letter, so "python is fun" becomes "Python Is Fun". This style is called title case and is used for headings and names.
Program
Original: python is a powerful programming language Capitalized: Python Is A Powerful Programming Language
How it works
split()breaks the sentence into a list of words.word[0].upper()is the first letter in capitals, andword[1:]is the rest of the word, from the second letter to the end.- Joining the two pieces gives the capitalized word, which is added to the list
capitalized. " ".join(capitalized)puts the words back together with single spaces.
Other ways to write it
Using title()
Python Is A Powerful Programming Language It'S Riya'S Book
title() is the quickest way, but it treats an apostrophe as the end of a word, so it's becomes It'S. It also makes the other letters small, so NASA would become Nasa.
Using string.capwords()
It's Riya's Python Book
string.capwords() splits on spaces, capitalizes each word and joins them again, so apostrophes are handled correctly. Extra spaces between words become one space.
Try it yourself
Make the program capitalize the last letter of each word instead, using word[:-1] + word[-1].upper().
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises