Using Python to Capitalize first letterIn 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.
Table of Contents
- How do you capitalize the first letter of a string?
- Using upper(), lower() and tittle()
- Closing thoughts - Python capitalize first letter
- Other Related Concepts
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.
How do you capitalize the first letter of a string?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
Code - Python capitalize first letter
The output of the code is as follows.
flexiple = "join are freelance community" print(flexiple.capitalize()) print(flexiple)
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.
Join are freelance community join are freelance community
Using upper(), lower() and tittle():Apart from using Python to capitalize the first letter it can also be used to change other cases.
The upper() method for example returns a string with all the characters in the upper case and the lower() method does the opposite.
The 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.
The output of this code is as follows
flexiple = "join are freelance community" print(flexiple.upper()) print(flexiple.lower()) print(flexiple.title()) print(flexiple)
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.
JOIN ARE FREELANCE COMMUNITY join are freelance community Join Are Freelance Community join are freelance community
Closing Thoughts - Python capitalize first letterLearning 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.