Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Python String capitalize()

In Python, String capitalize() is an inbuilt function that is used to make the first letter of a string as an uppercase letter.

  • This function converts all other letters of a string into Lowercase.

  • One important thing to note is that if the first character is a capital letter, in that case, the function will return the original string only.

  • If the string is empty, then using this function on such string will not lead to error, but will just return an empty string as output.

  • If we use this function with a numeric string like "45", again the function will return the same value.

Python String capitalize(): Syntax

Below we have a basic syntax of String capitalize() in Python:

string.capitalize()

In the above syntax, string denotes the string that is needed to be capitalized.

NOTE: Python capitalize() function does not contain any parameters.

Python String capitalize(): Return Value

This method returns a string with its first letter as an Uppercase letter while all others as Lowercase letters. In the case, if the string's first letter is in uppercase then it returns the original string.

Python String capitalize(): Basic Example

Below we have an example to show the working of String capitalize() function.

s1 = "hello studytonight"
print(s1.capitalize())


Hello studytonight

Python String capitalize() for Multiple Strings

Below we have an example to show you how to use String capitalize() for Multiple Strings.

string1 = "hello,"
string2 = "i am a developer"
print(string1.capitalize() + string2.capitalize())


Hello, I am a developer

Python capitalize() with other Object types like Number and None

If we use the capitalize() function with objects of different datatypes like a number or a None value, then we will get an error. Let's see both examples and the output:

Python capitalize() with Number:

In the python script below, we have tried using the capitalize() function with a numeric value:

x = 45
print(x.capitalize())


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'capitalize'

We get this error, because in Python only for String types, capitalize() is defined.

Python capitalize() with None:

Similarly, let's try using the capitalize() function with a None value:

x = None
print(x.capitalize())


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'capitalize'

Time For Live Example!

Let us see a live example where we will use capitalize with different strings:

Summary

In this tutorial, we learned the capitalize() method of Strings in Python that is used to make the first letter of a string as an uppercase letter. We saw the values returned by this method, we also saw a few examples; also how to apply this method on the number and none values further followed by a Live example.