Python Program to convert the first character of a string to Uppercase

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

  1. Start
  2. Take input: Prompt the user to enter a string.
  3. Check if the string is non-empty: Ensure that the string contains at least one character.
  4. Uppercase the first character:
    • Use the capitalize() or string slicing method to convert the first character of the string to uppercase.
  5. Display the result: Print the updated string with the first letter capitalized.
  6. 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

  1. Taking input from the user:
    The program uses the input() function to prompt the user to enter a string. The input is stored in the user_input variable.
  2. 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.
  3. Displaying the output:
    The print() function is used to display the modified string where the first character is in uppercase.

Python

7309

270

Related Articles