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:
- 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"
- Use the
upper()
method to convert the string to uppercase. Theupper()
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()
- 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!