Open In App

String capitalize() Method in Python

Last Updated : 05 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The capitalize() method in Python is used to change the first letter of a string to uppercase and make all other letters lowercase. It is especially useful when we want to ensure that text follows title-like capitalization, where only the first letter is capitalized.

Let’s start with a simple example to understand the capitalize() functions:

Python
s = "hello WORLD"
res = s.capitalize()
print(res)

Output
Hello world

Explanation: In this example, capitalize() method converts the first character “h” to uppercase and change the rest of characters to lowercase.

Syntax of capitalize() Method

s.capitalize()

Parameters

  • The capitalize() method does not accept any parameters.

Return Value

  • The method returns a new string with the first character capitalized and all other characters in lowercase. The original string remains unchanged.

Example of capitalize() Method

The capitalize() method only affects the first letter of the string and doesn’t capitalize each word in multi-word strings.

Python
s = "multiple WORDS IN a String"
res = s.capitalize()
print(res)

Output
Multiple words in a string

Explanation: Even though there are multiple words, only the first character of the entire string is affected, while the remaining words are converted to lowercase.

What happens if the first character is a number?

When the first character of a string is a number, capitalize() method does not alter it because it only affects alphabetical characters. Instead, it will simply convert any following alphabetical characters to lowercase.

Python
s = "123hello WORLD"
res = s.capitalize()
print(res)

Output
123hello world

Explanation: Since capitalize() only targets alphabetical characters for capitalization, the initial number remains unchanged. While rest of the characters follow the capitalization rule which results in “123hello world

Related Article:


Next Article
Article Tags :
Practice Tags :

Similar Reads