Skip to content

Python uppercase function upper() | convert string to Uppercase example

  • by

How do you convert a string to uppercase in Python?

The answer is Using a python inbuilt function upper(). Same as used lower() function in python. An upper() function converts all strings to lowercase characters (letters) into uppercase letters.

Python uppercase function upper

Syntax

The syntax of upper() method is:

string.upper()

Parameters

Python upper() function doesn’t take any parameters.

Return value

The Python upper() function returns the uppercased string of the given string. If there are lower characters in the string then it will also convert into uppercase characters.

Python upper function Examples

Let’s see the example of how to use upper() function in python.

Example 1: How to Convert a string to uppercase?

Use a python uppercase function – upper() followed by string variable.

create and initiated the string variable. A variable “str1” is has lowercase characters, which will be converted to uppercase char?

Another variable “str2″ has a combination of string and numeric value. It will also convert all characters in uppercase without an error.

# example string
str1 = "It should be uppercase!"
print(str1.upper())

# string with numbers
# all alphabets whould be lowercase
str2 = "L8w9rCas99!"
print(str2.upper())

Output:

IT SHOULD BE UPPERCASE!
L8W9RCAS99!

Example 2: Why/Where upper() function is used in a program?

Answer: It will use when you are trying to compare strings. See the below example without using a string in if conditions.

firstString = "PYTHON!"
 
secondString = "PyThOn!"
 
if(firstString == secondString):
    print("The strings are same.")
else:
    print("The strings are not same.")

Output: The strings are not same.

Both strings are the same but she letter are lowercase, so let’s try to solve this problem by using a python upper() function:-

firstString = "PYTHON!"

secondString = "PyThOn!"

if (firstString.upper() == secondString.upper()):
    print("The strings are the same.")
else:
    print("The strings are not same.")

Output: The strings are the same.

Example 3: How to convert Python uppercase first letter?

Answer: Use an index value of string and lower() function to convert a string first letter in the python program. And don’t forget to use Additional arithmetic operators to contact the remaining string.

See below example converting first letter into a uppercase letter.

str = "python!"

print(str[0].upper() + str[1:])

Output: Python!

Do comment if you have nay doubt and suggestion on the tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading