In this article, we will learn about python string capitalize() method with examples.

Python string capitalize() method

Python string class has a capitalize() method which converts the first character of a string to capital.

Remember that this method capitalizes only the first letter of string. All other characters of the string remain as it is. Example,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
str = 'codippa'
str_caps = str.capitalize()
print(str_caps) # prints Codippa
str = 'codippa' str_caps = str.capitalize() print(str_caps) # prints Codippa
str = 'codippa'
str_caps = str.capitalize()
print(str_caps) # prints Codippa

Syntax

capitalize() is a method of string class and so it is called on a string object.

Its syntax is

string.capitalize()

Parameters

Python string captialize() method does not take any parameters.

Return value

Python string capitalize() method returns a string whose first letter is capitalized.

Remember that capitalize() does not modify the string on which is is called. It creates a new string with first letter capitalized. Example,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
str = 'codippa is website'
str_caps = str.capitalize()
print(str)
print(str_caps)
str = 'codippa is website' str_caps = str.capitalize() print(str) print(str_caps)
str = 'codippa is website'
str_caps = str.capitalize()
print(str)
print(str_caps)

Output is

codippa is website
Codippa is website

capitalize() converts letters to lowercase

Python string capitalize() method converts ONLY the first letter to upper case.
This means that even if a string contains upper case characters, then all those are also converted to lower case. Example,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
str = 'codippa is WEBSITE'
str_caps = str.capitalize()
print(str_caps)
str = 'codippa is WEBSITE' str_caps = str.capitalize() print(str_caps)
str = 'codippa is WEBSITE'
str_caps = str.capitalize()
print(str_caps)

Look at the output

Codippa is website

First letter number

As stated earlier, capitalize() converts first character of a string to upper case.

But what if the first character is a number.

In that case, the string remains as it is. Example,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
str = '1 codippa'
str_caps = str.capitalize()
print(str_caps)
str = '1 codippa' str_caps = str.capitalize() print(str_caps)
str = '1 codippa'
str_caps = str.capitalize()
print(str_caps)

Output will be

1 codippa

If the string has upper case characters after the first letter, then they will be converted to lower case.

Hope the article was useful.