Write a Python program that takes a string as input and converts the first character of the string to uppercase. This program demonstrates string manipulation and handling user input.
Input-Output Examples
plaintext
Example 1:
Input: Enter a string: "hello world"
Output: "Hello world"
Example 2:
Input: Enter a string: "python programming"
Output: "Python programming"
Algorithm to convert the first character of a string to Uppercase
- Start
- Take input: Prompt the user to enter a string.
- Check if the string is non-empty: Ensure that the string contains at least one character.
- Uppercase the first character:
- Use the
capitalize()
or string slicing method to convert the first character of the string to uppercase.
- Use the
- Display the result: Print the updated string with the first letter capitalized.
- End
Python program to capitalize the first character of a string
python
# Python program to uppercase the first character of a string
# Take input from the user
user_input = input("Enter a string: ")
# Check if the string is non-empty and uppercase the first character
if user_input:
result = user_input[0].upper() + user_input[1:] # Convert first character to uppercase
else:
result = user_input # If string is empty, return it as is
# Display the result
print(f"The updated string is: {result}")
Python Program to uppercase the first character of a string using capitalize()
Method
python
# Python program to uppercase the first character of a string using capitalize()
# Take input from the user
user_input = input("Enter a string: ")
# Use capitalize() to uppercase the first character
result = user_input.capitalize()
# Display the result
print(f"The updated string is: {result}")
Code Explanation
- Taking input from the user:
The program uses theinput()
function to prompt the user to enter a string. The input is stored in theuser_input
variable. - Uppercasing the first character of the string:
- In the first approach, the program checks if the input string is non-empty. It then uses string slicing to convert the first character to uppercase (
user_input[0].upper()
), and concatenates the rest of the string (user_input[1:]
). - In the second approach, the
capitalize()
method is used, which automatically converts the first character to uppercase and leaves the rest of the string as is.
- In the first approach, the program checks if the input string is non-empty. It then uses string slicing to convert the first character to uppercase (
- Displaying the output:
Theprint()
function is used to display the modified string where the first character is in uppercase.