Python How to Convert String to Uppercase Easily
upper() method on a string to convert it to uppercase, like my_string.upper().Examples
How to Think About It
upper() method, which goes through each character and makes it uppercase if possible.Algorithm
Code
my_string = "hello world" uppercase_string = my_string.upper() print(uppercase_string)
Dry Run
Let's trace converting 'hello' to uppercase through the code
Original string
my_string = 'hello'
Convert to uppercase
uppercase_string = my_string.upper() # 'HELLO'
Print result
print(uppercase_string) outputs 'HELLO'
| Step | String Value |
|---|---|
| Initial | hello |
| 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
my_string = "Hello" uppercase_string = my_string.casefold().upper() print(uppercase_string)
my_string = "hello" uppercase_string = ''.join([char.upper() for char in my_string]) print(uppercase_string)
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.
| Approach | Time | Space | Best 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 |
upper() does not change the original string but returns a new one.upper() back to the original string without using an assignment, which leaves the original unchanged.