0
0
PythonHow-ToBeginner · 2 min read

Python How to Convert String to Uppercase Easily

Use the upper() method on a string to convert it to uppercase, like my_string.upper().
📋

Examples

Inputhello
OutputHELLO
InputPython3.9
OutputPYTHON3.9
Input123!@#
Output123!@#
🧠

How to Think About It

To convert a string to uppercase, think of changing every letter to its capital form. Python provides a simple way to do this by using the upper() method, which goes through each character and makes it uppercase if possible.
📐

Algorithm

1
Get the input string.
2
Call the <code>upper()</code> method on the string.
3
Return the new string with all letters in uppercase.
💻

Code

python
my_string = "hello world"
uppercase_string = my_string.upper()
print(uppercase_string)
Output
HELLO WORLD
🔍

Dry Run

Let's trace converting 'hello' to uppercase through the code

1

Original string

my_string = 'hello'

2

Convert to uppercase

uppercase_string = my_string.upper() # 'HELLO'

3

Print result

print(uppercase_string) outputs 'HELLO'

StepString Value
Initialhello
After upper()HELLO
💡

Why This Works

Step 1: Using the upper() method

The upper() method is built into Python strings and returns a new string with all lowercase letters changed to uppercase.

Step 2: No change to non-letters

Characters that are not letters, like numbers or symbols, stay the same because they have no uppercase form.

Step 3: Original string unchanged

The original string stays the same because upper() returns a new string instead of modifying the original.

🔄

Alternative Approaches

Using str.casefold() and then upper()
python
my_string = "Hello"
uppercase_string = my_string.casefold().upper()
print(uppercase_string)
This first normalizes the string to lowercase in a way that handles special cases, then converts to uppercase; useful for some languages but usually unnecessary.
Using a loop with str.upper() on each character
python
my_string = "hello"
uppercase_string = ''.join([char.upper() for char in my_string])
print(uppercase_string)
This manually converts each character; less efficient but shows how upper() works on single characters.

Complexity: O(n) time, O(n) space

Time Complexity

The upper() method checks each character once, so it takes time proportional to the string length, O(n).

Space Complexity

It creates a new string of the same length, so space used is also O(n).

Which Approach is Fastest?

Using the built-in upper() method is fastest and simplest compared to manual loops or extra normalization steps.

ApproachTimeSpaceBest For
str.upper()O(n)O(n)Simple and fast uppercase conversion
Loop with char.upper()O(n)O(n)Learning how upper() works on chars
casefold() + upper()O(n)O(n)Special language cases, less common
💡
Remember that upper() does not change the original string but returns a new one.
⚠️
Trying to assign the result of upper() back to the original string without using an assignment, which leaves the original unchanged.