In Python, the capitalize function serves to transform the initial character of a string into an uppercase letter while leaving the remainder of the string untouched. This method exclusively modifies the first character, preserving the case of all subsequent characters in the string.
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
In this section, we will examine multiple examples to illustrate how the string capitalize method functions in Python.
Python String capitalize Method Example 1
# Python capitalize() function example
# Variable declaration
str = "logicpractice"
# Calling function
str2 = str.capitalize()
# Displaying result
print("Old value:", str)
print("New value:", str2)
Output:
Old value: logicpractice
New value: ExampleTech
Python String Capitalize Method Example 2
What should be done if the initial character is already in uppercase?
# Python capitalize() function example
# Variable declaration
str = "ExampleTech"
# Calling function
str2 = str.capitalize()
# Displaying result
print("Old value:", str)
print("New value:", str2)
Output:
Old value: ExampleTech
New value: ExampleTech
It provides the identical string without making any modifications.
Python String Capitalize Method Example 3
What happens when the initial character is a digit or a non-alphabetic symbol? This approach does not modify the character if it is not classified as a string character.
# Python capitalize() function example
# Variable declaration
str = "#logicpractice"
# Calling function
str2 = str.capitalize()
# Displaying result
print("Old value:", str)
print("New value:", str2)
print("--------digit---------")
str3 = "1-logicpractice"
str4 = str3.capitalize()
print("Old value:", str3)
print("New value:", str4)
Output:
Old value: #logicpractice
New value: #logicpractice
--------digit---------
Old value: 1-logicpractice
New value: 1-logicpractice