learn python string capitalize() with 3 example

The capitalize() method is a built-in string method in Python that is used to capitalize the first character of a string. Here’s the syntax of the method:

string.capitalize()

The capitalize() method takes no arguments and returns a new string with the first character capitalized. If the first character is already uppercase or non-alphabetic, the method returns the string unchanged.

Here’s an example of using the capitalize() method:

string = "hello world"
capitalized_string = string.capitalize()
print(capitalized_string)

Output:

Hello world

Example 1

Capitalize first letter of each word in a sentence.

sentence = "generally the pythons are better than anything else at killing"
capitalized_sentence = " ".join(word.capitalize() for word in sentence.split())
print(capitalized_sentence)

Output:

Generally The Pythons Are Better Than Anything Else At Killing

Example 2

Capitalize first letter of a string, and convert the rest to lowercase.

string = "hELLo WOrLD"
capitalized_string = string.capitalize()
print(capitalized_string)

Output:

Hello world

Example 3

Suppose you have a list of names in lowercase, and you want to print out the names with the first letter capitalized. You can use the capitalize() method to achieve this as shown below.

names = ["john", "jane", "doe", "harry", "susan"]
for name in names:
  capitalized_name = name.capitalize()
  print(capitalized_name)

Output:

John
Jane
Doe
Harry
Susan