In Python, String capitalize() is an inbuilt function that returns a string copy with only its first character capitalized. If the string contains the first capital letter, the original string would be restored.
The syntax of the method is: str.capitalize()
Key Points :
• Return Type: String
• Parametric Values: Python capitalize() method does not contain any parameters.
• Conversion of the first string character to uppercase only.
• The original string does not change. The new variable name is saved for the modified string.
• If the string is empty, this method does not lead to an error for that string but returns an empty string for the result.
• When the feature uses a numeric string like “786,” the function returns the same value.
Below is the python program to demonstrate the capitalize() function:
# Python program to demonstrate the # use of capitalize() function str = "Hi Technology Motivator"; print (str.capitalize())
When we run above the program, the outcome is as follows:
Output : Hi technology motivator
We’ll be covering the following topics in this tutorial:
Python String capitalize() for Multiple Strings
Below is the python program to demonstrate the capitalize() for Multiple Strings.
# Python capitalize method Example str = "hello, " str2 = "technology motivator" print(str.capitalize() + str2.capitalize())
When we run above the program, the outcome is as follows:
Hello, Technology motivator
Python capitalize() with other Object types like Number and None
We get an error when we use capitalize() for objects with different data types like a number or a Zero value. Let’s see the examples as well as the result:
Python capitalize() with Number:
Below is the python program to demonstrate the capitalize() function with a numeric value:
x = 786 print(x.capitalize())
When we run above the program, the outcome is as follows:
Traceback (most recent call last): File "main.py", line 2, in <module> print(x.capitalize()) AttributeError: 'int' object has no attribute 'capitalize'
Below are several other functions that we can use to work with string in Python 3