What is string.capitalize() in Python?

The capitalize() method converts the first alphabetical character of a string to uppercase and the remaining characters to lowercase, and returns that string.

Syntax

string.capitalize()

Example 1

string = "educatiVE.IO"
print('old string - ', string)
print('capitalized string - ', string.capitalize());

In the code above, we created an educatiVE.IO string, and called the capitalize method which will make the first character of the string uppercase and the remaining characters of the string lowercase. It will return the converted string as a new string.

Example 2

If the first character is a non-alphabetical character then all characters of the string are converted to lowercase.

string = "$educatiVE.IO"
print('old string - ', string)
print('capitalized string - ', string.capitalize());
string = " educatiVE.IO"
print('\nold string - ', string)
print('capitalized string - ', string.capitalize());

In the code above, we created an $educatiVE.IO string and called the capitalize method. In this case, the first character is a non-alphabetical character so it is skipped and the remaining characters of the string are converted to lowercase. The converted string is returned as a new string.

Similarly, we created a string with space as the first character for this case. The first character is skipped, and the remaining characters are converted to lowercase.