Python capitalize() Method

Python Basic Tutorials

Python Advanced Tutorials

Python capitalize() Method

The capitalize() method converts the first character of a string to uppercase and makes all other characters lowercase.

Syntax

str.capitalize()

Parameters

No parameters are required.

Returns

Returns a copy of the string with the first character capitalized and the rest in lowercase.

Example

#!/usr/bin/python3

str = "hello world"
print("Original string: ", str)
print("Capitalized string: ", str.capitalize())

Output

Original string:  hello world
Capitalized string:  Hello world

Explanation

The capitalize() method capitalizes the first letter of the string and converts all other letters to lowercase. If the string is empty or contains only whitespace, it returns an empty string.

Additional Notes

  • If the first character is already uppercase, no change occurs.
  • If the string contains non-alphabetic characters at the beginning, they remain unchanged.
  • This method does not modify the original string; it returns a new string.

See Also

  • title() – Converts the first letter of each word to uppercase.
  • upper() – Converts all characters to uppercase.
  • lower() – Converts all characters to lowercase.
© 2024 . All rights reserved.