How to convert to Uppercase in Python?

Consider a string string_1 = 'Python Programming". The string_1 when converted to uppercase changes to "PYTHON PROGRAMMING". This article discusses different approaches to convert a string to uppercase in python.

Converting to uppercase using upper()

In Python, upper() is an inbuilt function that converts all the characters to uppercase letters. The uppercase() function returns an uppercase string and doesn't take any parameter. The syntax for the upper() method is given below.

#syntax:
string.upper()

Let us consider a string string_1 = "Welcome To Python" . string_1.upper() returns the output as "WELCOME TO PYTHON".

string_1 = "Welcome To Python"
print("Original string_1: ", string_1)
print("Uppercase string: ",string_1.upper())

Output

Original string_1:  Welcome To Python
Uppercase string:  WELCOME TO PYTHON

Converting to uppercase using for loop

Consider a string string_1 = "Python Programming". A for loop iterates over the string. If the character of the string is in lowercase, the ord() function gets the ASCII value of the respective character and stores it in variable val_1.

The val_1 is subtracted by 32(the difference between ASCII values of 'A' and 'a' is 32) to get the ASCII value of the uppercase letter of the same typeface and stores it in the variable val_2. The chr() function converts the val_2 ASCII value to its corresponding character and concatenates it to the variable upper_case.

If the character present in the string_1 is in uppercase it is directly concatenated to variable upper_case.

string_1 = "Python Programming"
print("Original string_1", string_1)
upper_case = ""
for ch in string_1:
    if ch.islower():
        val_1 = ord(ch)
        val_2 = val_1 - 32
        upper_case += chr(val_2)
    else:
        upper_case += ch
print("Uppercase: ", upper_case)

The above program returns the output as

Original string_1 Python Programming
Uppercase:  PYTHON PROGRAMMING
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions