Skip to main content

How to convert a string to uppercase in Python

How to convert a string to uppercase in Python.

Here's a detailed step-by-step tutorial on how to convert a string to uppercase in Python:

  1. Start by defining a string variable that you want to convert to uppercase. For example, let's say the string is "hello world". You can define the string variable like this:
string = "hello world"
  1. Use the upper() method to convert the string to uppercase. The upper() method is a built-in method in Python that returns a new string where all characters are converted to uppercase. Assign the result to a new variable to store the uppercase string. Here's an example:
uppercase_string = string.upper()
  1. You can now use the uppercase_string variable to access the converted uppercase string. For example, you can print it out to see the result:
print(uppercase_string)

The output of the above code will be:

HELLO WORLD

That's it! You have successfully converted a string to uppercase in Python.

Here's another example that demonstrates the conversion of user input to uppercase:

# Get user input
string = input("Enter a string: ")

# Convert to uppercase
uppercase_string = string.upper()

# Print the uppercase string
print("Uppercase string:", uppercase_string)

This code prompts the user to enter a string, converts it to uppercase using the upper() method, and then prints the uppercase string.

You can also convert a string to uppercase using the str.upper() function, which is an alternative way:

string = "hello world"
uppercase_string = str.upper(string)
print(uppercase_string)

Both approaches will give you the same result.

I hope this tutorial helps you understand how to convert a string to uppercase in Python!