Convert first character of a string to uppercase in Python
This post will discuss how to convert the first character of a string to uppercase in Python.
1. Using str.title() function
You can use str.title() to get a title cased version of the string. This converts the first character of each word in the string to uppercase and the remaining characters to lowercase. The following example demonstrates this.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = 'techiE delighT' s = s.title() print(s) # Techie Delight |
2. Using str.capitalize() function
You can use str.capitalize() to get a string with its first character capitalized and remaining characters lowercased, as demonstrated in the following example:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = 'techiE DelighT' s = s.capitalize() print(s) # Techie delight |
3. Using Slicing
If you just need to convert the first character to uppercase and leaving other characters untouched, you can use the upper() function with slicing, as shown below:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = 'techiE DelighT' s = s[0].upper() + s[1:] print(s) # TechiE DelighT |
That’s all about converting the first character of a string to uppercase in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)