Editor

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

capitalize_each_word.py
text = "python is a powerful programming language" # or: text = input("Enter a sentence: ")
words = text.split()
capitalized = []
for word in words:
# First letter in capitals, the rest of the word unchanged
capitalized.append(word[0].upper() + word[1:])
result = " ".join(capitalized)
print("Original: ", text)
print("Capitalized:", result)
Output
Original:    python is a powerful programming language
Capitalized: Python Is A Powerful Programming Language

How it works

  1. split() breaks the sentence into a list of words.
  2. word[0].upper() is the first letter in capitals, and word[1:] is the rest of the word, from the second letter to the end.
  3. Joining the two pieces gives the capitalized word, which is added to the list capitalized.
  4. " ".join(capitalized) puts the words back together with single spaces.

Other ways to write it

Using title()

Using title()
text = "python is a powerful programming language"
print(text.title())
# title() starts a new word after an apostrophe
print("it's riya's book".title())
Output
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()

Using string.capwords()
import string
text = "it's riya's python book"
print(string.capwords(text))
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises