Python String capitalize() Method

In Python, the capitalize() method is used to convert the first character of the string into uppercase without altering the whole string. It changes the first character only and skips rest of the string unchanged.

Python String capitalize() Method Syntax

It has the following syntax:

capitalize()  

Parameters

It does not required any parameter.

Return Type

It returns a modified string.

Different Examples for Python String capitalize() Method

Here, we are going to take several examples to demonstrate the working of the string capitalize() Method in Python.

Python String capitalize() Method Example 1

# Python capitalize() function example  

# Variable declaration  

str = "pythonapp"  

# Calling function  

str2 = str.capitalize()  

# Displaying result  

print("Old value:", str)  

print("New value:", str2)

Output:

Old value: pythonapp
New value: Pythonapp

Python String Capitalize() Method Example 2

What if first character already exist in uppercase.

# Python capitalize() function example  

# Variable declaration  

str = "Pythonapp"  

# Calling function  

str2 = str.capitalize()  

# Displaying result  

print("Old value:", str)  

print("New value:", str2)

Output:

Old value: Pythonapp
New value: Pythonapp

It returns the same string without any alteration.

Python String Capitalize() Method Example 3

What if first character is a digit or non-alphabet character? This method does not alter character if it is other than a string character.

# Python capitalize() function example  

# Variable declaration  

str = "#pythonapp"  

# Calling function  

str2 = str.capitalize()  

# Displaying result  

print("Old value:", str)  

print("New value:", str2)  

print("--------digit---------")  

str3 = "1-tpointtech"  

str4 = str3.capitalize()  

print("Old value:", str3)  

print("New value:", str4)

Output:

Old value: #pythonapp
New value: #pythonapp
--------digit---------
Old value: 1-pythonapp
New value: 1-pythonapp

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *