Python String capitalize() Function

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!


References

Python Functions

Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 211
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy