String in Python has built-in functions for almost every action to be performed on a string. Python String capitalize() function is used to convert only the first character to the uppercase letter, rest all characters are lowercase.
Key Points :
- Return Type: String
- Parametric Values: No parameters can be parsed onto capitalize() function.
- Converts only the first character of a string to uppercase.
- It does not modify the original string. The modified string is saved with a new variable name.
Example: Given String – “Have a Nice Day” Or “Have A NICE DAY” Or “have a nice day” Or “Have a nice day”
Capitalized String: “Have a nice day” (for all the above-given strings)
Syntax :
str_name.capitalize()
str_name here refers to the string to be capitalized. And, capitalize() is inbuilt string function in python.
Basic Example
str_name = "hi there!"
new_str = str_name.capitalize()
print('The New Capitalized String is ',new_str)
Output: Hi there!
Different Cases :
Examples of different cases are given below –
Case 1: All the characters in a string are uppercase
str_name = "HI THERE"
new_str = str_name.capitalize()
print('The New Capitalized String is ',new_str)
Output: Hi there!
Case 2: The first alphabet of every word in a string containing multiple words is uppercase
str_name = "Hi There!"
new_str = str_name.capitalize()
print('The New Capitalized String is ',new_str)
Output: Hi there!
Case 3: Randomly any character in a string is uppercase
str_name = "hI tHeRE!"
new_str = str_name.capitalize()
print('The New Capitalized String is ',new_str)
Output: Hi there!
Case 4: Non-alphanumeric or Numeric first character
str_name = "! hi there"
new_str = str_name.capitalize()
print('The New Capitalized String is ',new_str)
Output: ! hi there!