In this short tutorial, we look at how you could use Python to Capitalize the first letter. We also look at all the other methods that can be used to change cases.
This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.
- How do you capitalize the first letter of a string?
- Using upper(), lower() and tittle()
- Closing thoughts - Python capitalize first letter
While using Python you would deal with a lot of strings and sometimes you might want to display them in a particular case. This may not be a problem if the string is hardcoded, however, while using dynamic data e.g.: Displaying the user name on the top of the screen. The data for this might contain strings in various cases so it is important to fail-proof such instances.
This article is a tutorial about the same.
The first letter of a string can be capitalized using the
capitalize() function. This method returns a string with the first letter capitalized. If you are looking to capitalize the first letter of the entire string the
title() function should be used.
The following is the syntax to use python to capitalize first letter:
Here “string” refers to the string you are looking to capitalize
flexiple = "join are freelance community" print(flexiple.capitalize()) print(flexiple)
The output of the code is as follows.
Join are freelance community join are freelance community
As you can see above, the first letter of the first string was capitalized. After which I have again printed the original string to show you that the original string has not been changed.
Apart from using Python to capitalize the first letter it can also be used to change other cases.
upper() method for example returns a string with all the characters in the upper case and the
lower() method does the opposite.
title() method is used to capitalize the first letter of all the words in a string.
The syntax is similar to capitalize, you can see the implementation in the code section below.
flexiple = "join are freelance community" print(flexiple.upper()) print(flexiple.lower()) print(flexiple.title()) print(flexiple)
The output of this code is as follows
JOIN ARE FREELANCE COMMUNITY join are freelance community Join Are Freelance Community join are freelance community
As you can see in each method the case is changed accordingly and I have again printed the string to show that the original string has not changed.
Learning to use Python to capitalize the first letter of a string may not be a very important topic but this is something that developers are expected to know.
Practicing and being aware of the various methods would help you when you face such cases.