String capitalize() Method in Python

Python String capitalize() Method

The capitalize() method is a built-in string method in Python that is used to modify a string by capitalizing its first character while converting all other characters in the string to lowercase. It does not alter any characters beyond the first one.

Here's the syntax of the capitalize() method:

string.capitalize()

Here's what this method does:

  1. It takes the string on which it is called (string) and capitalizes the first character of that string.
  2. It converts all the other characters in the string to lowercase.
  3. It returns the modified string with the first character capitalized and the rest of the characters in lowercase.

Let's see some examples to understand better how it works:

Example 1:

text = "hello, world!"
capitalized_text = text.capitalize()
print(capitalized_text)  # Output: "Hello, world!"

Example 2:

name = "john doe"
capitalized_name = name.capitalize()
print(capitalized_name)  # Output: "John doe"

Example 3:

text = "GREAT"
capitalized_text = text.capitalize()
print(capitalized_text)  # Output: "Great"

Keep in mind that the capitalize() method does not modify the original string; it returns a new string with the desired modifications. If the original string is empty or consists of only whitespace characters, the capitalize() method will return the same string without any changes.