In Python, capitalizing the first character of a string can be done using the
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
string = input("Enter a string: ") capitalized_string = string.capitalize() print(capitalized_string)
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
We then call the
capitalize() method on this string and assign the result to the variable
Finally, we print out the capitalized string using the
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() print(capitalized_string)
In this example, the original string contains a mix of alphabetic and non-alphabetic characters.
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
By using this method, we can easily transform any string to have a capitalized first character.