NumPy Upper Function

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to use the upper() function in the char module of the NumPy library. This function is used to convert all lowercase characters of a string to uppercase. If there are no lowercase characters in the given string, it returns the original string. We will cover the syntax required to use this function, its returned values, and provide examples of its use.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Import NumPy Library

The first step is to import the NumPy library using the syntax below:

import numpy as np

Apply upper() function on a Simple String

In this step, we will use the upper() function on a simple string. We will create a variable a that contains the string "this is a string in NumPy" and apply the upper() function on it. Here is an example code snippet:

a = "this is a string in NumPy"
print("The original string:")
print(a)
print("\n")
print("Applying the upper() method:")
x = np.char.upper(a)
print(x)

Apply upper() function on a String in Uppercase

In this step, we will use a string that is already in uppercase, then check the output for the same. We will create a variable a that contains the string "THIS IS AN UPPERCASE STRING" and apply the upper() function on it. Here is an example code snippet:

a="THIS IS AN UPPERCASE STRING"
print("The original string:")
print(a)
print("\n")
print("Applying the upper() method:")
x=np.char.upper(a)
print(x)

Apply upper() function on an Array of Strings

In this step, we will create an array of strings and then use the upper() function with the array. It will convert all the string elements to uppercase. We will create an array arr that contains the strings "what aRE YOUR", "plans for Tonight", "will you", and "study tonight" and apply the upper() function on it. Here is an example code snippet:

arr = np.array(['what aRE YOUR', 'plans for Tonight', 'will you','study tonight'])
print ("The original Input array : \n", arr)

output = np.char.upper(arr)
print ("The output array: ", output)

Summary

In this lab, we covered the upper() function in the NumPy library. We covered how it is used with its syntax and values returned by this function along with multiple code examples. By following the above steps, you now have a better understanding of how to use the upper() function in the char module of the NumPy library.

Other Python Tutorials you may like