How to capitalize first character of string in Python

The problem of case changes a string is quite common and has been discussed many times. Sometimes, we might have a problem like this in which we need to convert the initial character of string to upper case. Let’s discuss certain ways in which this can be performed.

Method #1 : Using string slicing + upper()
This task can easily be performed using the upper method which uppercases the characters provided to it and slicing can be used to add the remaining string after the lowercase first character.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Initial character upper case
# Using upper() + string slicing
  
# initializing string 
test_str = "geeksforgeeks"
  
# printing original string 
print("The original string is : " + str(test_str))
  
# Using upper() + string slicing
# Initial character upper case
res = test_str[0].upper() + test_str[1:]
  
# printing result 
print("The string after uppercasing initial character : " + str(res))

chevron_right


Output :

The original string is : geeksforgeeks
The string after uppercasing initial character : Geeksforgeeks

 

Method #2 : Using capitalize()
We can use inbuilt method to perform this task. This method is recommended to solve this problem and performs the task of converting to upper case internally.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Initial character upper case
# Using capitalize() + string slicing
  
# initializing string 
test_str = "geeksforgeeks"
  
# printing original string 
print("The original string is : " + str(test_str))
  
# Using capitalize() + string slicing
# Initial character upper case
res = test_str.capitalize()
  
# printing result 
print("The string after uppercasing initial character : " + str(res))

chevron_right


Output :

The original string is : geeksforgeeks
The string after uppercasing initial character : Geeksforgeeks



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.