NumPy Swapcase Function

PythonPythonBeginner
Practice Now

Introduction

In this lab, we will cover the step-by-step process of using the Swapcase() function of the char module in the Numpy library. This tutorial is for those who want to manipulate strings in Numpy and change the cases of the characters in their string.

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.

Importing Numpy library

The first step is to import the Numpy library into your Python environment. You can use the following code snippet to import this library:

import numpy as np

Creating an Array with Strings

The second step is to create an array containing strings. You can use the np.array() function to create a new array. Here is an example code snippet:

arr = np.array(['Numpy', 'NumPy', 'numpy'])

Using the Swapcase() function

The third step is to use the Swapcase() function to change the cases of the characters in the array's string. You can use the np.char.swapcase() function to perform this operation. Here is an example code snippet:

arr_swapcase = np.char.swapcase(arr)

Printing the Result

Finally, you need to print out the result of the Swapcase() function. You can use the print() function to display the new array with change cases. Here is an example code snippet:

print("Original array:", arr)
print("Swapped cases array:", arr_swapcase)

Example

Let's understand the Swapcase() function using an example code:

import numpy as np

## Creating a string array
arr = np.array(['This is NumPy Tutorial', 'Swapcase function', 'python'])

## Swapping cases of all characters in the string
arr_swapcase = np.char.swapcase(arr)

## Printing the results
print("Original Array: ", arr)
print("Swapped Cases Array: ", arr_swapcase)

The output of the above code will be:

Original Array: ['This is NumPy Tutorial' 'Swapcase function' 'python']
Swapped Cases Array: ['tHIS IS nUMpY tUTORIAL' 'sWAPCASE FUNCTION' 'PYTHON']

Summary

In this lab, we learned about the Swapcase() function of the char module in the Numpy library, which is used mainly to return an element-wise copy of the string with the uppercase characters of the string converted to lowercase and lowercase characters converted to uppercase. It swaps or changes the case of the characters in a given string. In this lab, we covered the step-by-step process of using the function to manipulate strings in Numpy.

Other Python Tutorials you may like