string capitalize() in Python

In this article, we would cover string capitalize() method in Python. The capitalize() method returns a string wherein all the characters of the string is converted to lowercase except the first character. It converts the first character of the string to uppercase.

This may seem familiar with title() method, which we have already discussed. But, it is different. In title() method, the first character of the every word in a string is converted to uppercase while rest of the characters stay in lowercase. Whereas, with capitalize() method – the first character of the string is converted to uppercase. It just converts other characters to lowercase irrespective of whether they are lowercase or uppercase.

To understand the concept better, we discuss it with couple of examples next.

string capitalize() in Python

Example I. Let’s say we have a string x

x = "hello, how are you?"

Now, we store the outcome of capitalize() method in variable y.

y = x.capitalize()

Furthermore, to display the result – we use print() method –

print(y)

It would return with –

Hello, how are you?

Here, it just converts first character of the string to uppercase. Rest all are lowercase.

Example II. Now, consider a scenario in which few more characters are in uppercase. In that case, how it will respond?

x = "hello, How ARE YoU?"

again, store the outcome of capitalize() method in variable y

y =  x.capitalize()

To display the result –

print(y)

It should return with –

Hello, how are you?

Now, observe that – It converts the first character to uppercase while rest of the characters to lowercase. How ARE YoU? is now how are you?

Example III. What if we have an integer as the first letter? How capitalize() method will modify things?

x = "3hello, How ARE you?"

store the outcome in variable y,

y = x.capitalize()

To get the result, use print() method –

print(y)

Lastly, it would return with –

3hello, how are you?

It ignores the first character as its an integer. And, it converts other characters to lowercase.

In conclusion, we have discussed string capitalize() method in Python.

Similar Posts