Python String capitalize() Method – Tutorial with Examples

Python String capitalize() Method

The capitalize() method is a built-in method in Python that capitalizes the first character of a string. This method does not change the original string but returns a new string with the first character capitalized. If the string is empty, the method returns an empty string.

Syntax

The syntax of the capitalize() method is as follows:

string.capitalize()

Here, string is the string to be capitalized.

Return Value

The capitalize() method returns a new string with the first character capitalized. If the string is empty, the method returns an empty string.

Examples

Here are three different examples of how to use the capitalize() method in Python:

Example 1:

The following example demonstrates how to use the capitalize() method to capitalize the first character of a string:

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

Output:

Hello world

In this example, we create a string “hello world” and then use the capitalize() method to capitalize the first character of the string. The method returns a new string with the first character capitalized, which we then print to the console.

Example 2:

The following example demonstrates how to use the capitalize() method to capitalize the first character of each word in a string:

string = "hello world"
capitalized_string = " ".join(word.capitalize() for word in string.split())
print(capitalized_string)

Output:

Hello World

In this example, we create a string “hello world” and then use the split() method to split the string into a list of words. We then use a list comprehension to apply the capitalize() method to each word in the list. Finally, we use the join() method to join the capitalized words back together into a single string with the first character of each word capitalized.

Example 3:

The following example demonstrates how to use the capitalize() method to capitalize only the first character of a string and leave the rest of the characters in lowercase:

string = "hELLO wORLD"
capitalized_string = string.capitalize()
print(capitalized_string)

Output:

Hello world

In this example, we create a string “hELLO wORLD” and then use the capitalize() method to capitalize only the first character of the string and leave the rest of the characters in lowercase.

Use Cases

The capitalize() method is useful in situations where you want to capitalize the first character of a string or the first character of each word in a string. This method is often used in text processing applications, such as in natural language processing or text classification tasks.

Leave a Reply

Your email address will not be published. Required fields are marked *