In Python, the string class (Str) provides a member function upper() to convert a string into upper case.

Table of Contents

Syntax of upper() method

str.upper()

Parameters:

  • It does not accept any parameter.

Returns:

  • It returns an uppercase copy of the calling string object. It means all characters in the returned string will be in uppercase.
  • If there are no lowercase characters in the string, then it will return the original string. Let’s understand more about it with the help of some examples.

Examples of string function upper() in Python

Convert a string to uppercase

str_obj = 'sample string'

str_obj = str_obj.upper()

print(str_obj)

Output:

SAMPLE STRING

It returned a copy of the calling string object, and in the returned copy, all the lowercase characters were converted to uppercase characters. Then we assigned the uppercase copy of the string to the original string object. It gave an effect that we have converted all the characters to upper case in a string.

Convert a string containing letters and numbers to uppercase

str_obj = 'sample 123 string'

str_obj = str_obj.upper()

print(str_obj)

Output

SAMPLE 123 STRING

The string had some lowercase characters and numbers. So the upper() function converted all the lower case characters to upper case characters. Whereas the numbers and other non-alphabet characters remained as they were in the original string.

Convert a character to upper case in Python using upper()

There is no data type for individual characters in Python. A single character is also a python string object. So, we can use the upper() method to convert a character to upper case. For example,

str_obj = 'b'

str_obj = str_obj.upper()

print(str_obj)

Output:

B

Comparing two strings by converting them into uppercase

Generally, the upper() function is used in a case insensitive comparison of two strings. For example, we convert both the strings to upper case before comparing them,

str_obj_1 = 'sample string'
str_obj_2 = 'sample STRING'

if str_obj_1.upper() == str_obj_2.upper():
    print('Both strings are similar')
else:
    print('Both strings are not similar')

Output

Both strings are similar

Summary

We can use the upper() function to convert all the lowercase characters in a string to the uppercase characters.

Join a list of 2000+ Programmers for latest Tips & Tutorials