AppDividend
Latest Code Tutorials

How to Convert First Character to Capital in Python

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

Convert First Character to Capital in Python

To convert the first character of a String to capital in Python, use the capitalize() method. The String capitalize() is a built-in Python function used to make the first letter of the string capital.

If the String already has its first letter capital, the function capitalize() returns the original String only. 

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.

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 capitalized, you can use String.capitalize() method.

That’s it for this tutorial.

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.