Write a Python Program to Capitalize the First Character of a String

In Python, capitalizing the first character of a string can be done using the capitalize() method.

This method returns a copy of the string with the first character capitalized and all other characters in lowercase.

To demonstrate this, let’s write a simple program that prompts the user to enter a string and then capitalizes the first character of that string using the capitalize() method:

string = input("Enter a string: ")
capitalized_string = string.capitalize()

In the above program, we first prompt the user to enter a string using the input() function. We then assign this string to the variable string.

We then call the capitalize() method on this string and assign the result to the variable capitalized_string.

Finally, we print out the capitalized string using the print() function.

Let’s test this program out by entering the string “hello, world”:

Enter a string: hello, world
Hello, world

As we can see, the first character of the string has been capitalized.

It’s worth noting that if the string contains non-alphabetic characters, the capitalize() method will only capitalize the first alphabetic character:

string = "123 hello, world!"
capitalized_string = string.capitalize()

In this example, the original string contains a mix of alphabetic and non-alphabetic characters.

However, the capitalize() method only capitalizes the first alphabetic character, resulting in the output:

123 hello, world!

In conclusion, capitalizing the first character of a string in Python is a simple task that can be accomplished using the capitalize() method.

By using this method, we can easily transform any string to have a capitalized first character.