Yandex

Python String capitalize() – Capitalize First Letter of a String

Python String capitalize() Method

The capitalize() method in Python is used to convert the first character of a string to uppercase and the rest to lowercase.

This method is useful when you want to format strings to look like proper sentences or names.

Syntax

string.capitalize()

Returns:

  • A new string with the first character capitalized and the rest in lowercase.

Example 1: Basic Usage

text = "hello world"
print(text.capitalize())
Hello world

Example 2: All Caps to Capitalized

text = "PYTHON IS FUN"
print(text.capitalize())
Python is fun

Example 3: Already Capitalized

text = "Python programming"
print(text.capitalize())
Python programming

Example 4: Starting with Non-letter Character

text = "123hello"
print(text.capitalize())
123hello

Note: Only the first letter is affected. If the first character is not a letter, nothing changes.

Use Cases

  • Formatting user input (e.g., names, titles)
  • Creating proper sentence case for display
  • Ensuring consistency in strings for comparisons

Does it Modify the Original String?

No. Strings in Python are immutable. capitalize() returns a new string and does not change the original one.

Common Mistakes

  • Assuming it capitalizes every word – it only affects the first character.
  • For capitalizing every word, use title() instead.

Interview Tip

capitalize() is often used in string normalization or preprocessing tasks before comparison or display.

Summary

  • capitalize() returns a new string with the first character uppercase and the rest lowercase.
  • Original string remains unchanged.
  • Non-letter first characters are not affected.

Practice Problem

Write a program that takes a sentence as input and prints the capitalized version.

sentence = input("Enter a sentence: ")
print("Capitalized:", sentence.capitalize())


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M