AppDividend
Latest Code Tutorials

Python String capitalize() Method Example

0

Python String capitalize() function in python is used to make the first letter of the string capital. If the string already has its first letter capital, then the function capitalize() returns the original string only.  In Python, the capitalize() method converts the first character of a string to the capital (uppercase) letter. If the string has its first character as capital, then it returns the original string.

Python String capitalize()

In Python string capitalize() method converts the first character of a string to the uppercase letter and lowercases all other characters, if any.

Syntax

string.capitalize()

Here the string contains the string of which we want to capitalize the first letter.

Parameters

The string capitalize() method doesn’t contain any parameters.

Return Value

The method returns a string that has its first character as capital.

Example programs on the Python capitalize()

Write a program to demonstrate the use of the capitalize function.

# app.py

s1="hello my name is rohit"
print(s1.capitalize())

See the output.

➜  pyt python3 app.py
Hello my name is rohit
➜  pyt

Write multiple strings and show the use of the capitalize function.

# app.py

string1="hello,"
string2="i am alien"
print(string1.capitalize()+string2.capitalize())

See the output.

➜  pyt python3 app.py
Hello,I am alien
➜  pyt

Write a program to capitalize on a particular substring of a string using capitalize function.

# Here I will capitalize character c of coding word.

string_var = "ilovecoding"
string_var1 = string_var[5::]
string_var2 = string_var[:5:]
print(string_var2+string_var1.capitalize())

See the output.

➜  pyt python3 app.py
iloveCoding
➜  pyt

If you only need the first letter to be capitalized, you can use string.capitalize() method.

Finally, Python String capitalize() Method Example is over.

Recommended Posts

Python String center()

Python string casefold()

Python String expandtabs()

Python dict() method

Python hex() function

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.