Signup/Sign In

NumPy center() function

In this tutorial, we will cover center() function of the char module in the Numpy library.

The center() function is used to return a copy of the input array of the required width so that the input array of a string is centered and padded on the left and right with fillchar.

  • In simple terms, this function creates and returns a new string from the input string and this new string is padded with the specified characters on both left and right side.
  • This function basically calls str.center for every element of the array.

Syntax of numpy.char.center():

The syntax required to use this function is as follows:

numpy.char.center(a, width, fillchar=' ')

The above syntax indicates that center() function takes two parameters.

Parameters:

Let us now take a look at the parameters of this function:

  • a
    This parameter indicates an array of strings or a string on which the function will be applied.

  • width
    This parameter indicates the length of the resulting string.

  • fillchar
    This parameter indicates the padding character to be used as the filler and the default value of this parameter is whitespace.

Returned Values:

This function returns a new string that is padded with characters specified.

Example 1: With a string

The code snippet is as follows where we will use center() function with a simple string:

import numpy as np   

a1 = "StudyTonight!"
print("Padding the Inut string through left and right with the fill char ^:");  
x = np.char.center(a1, 30, '^')
print(x)


Padding the Inut string through left and right with the fill char ^:
^^^^^^^^StudyTonight!^^^^^^^^^

Example 2: With an array of strings

In the code below, we will be using the center() function for an array of strings. This function acts in the same way for each string element of the array, like it did for a single string in the example above.

import numpy as np 
 
arr= np.array(['StudyTonight', 'Online', 'Portal']) 
print("The Original Array :") 
print(arr) 

output = np.char.center(arr, 30, '^')
print("\nThe Resultant array :") 
print(output)


The Original Array :
['StudyTonight' 'Online' 'Portal']

The Resultant array :
['^^^^^^^^^StudyTonight^^^^^^^^^' '^^^^^^^^^^^^Online^^^^^^^^^^^^'
'^^^^^^^^^^^^Portal^^^^^^^^^^^^']

Summary

In this tutorial, we covered the center() function used to add padding to string or string elements present in an array. We covered two different code examples showing the center() function in action for both a single string and for an array of strings.



About the author:
Aspiring Software developer working as a content writer. I like computer related subjects like Computer Networks, Operating system, CAO, Database, and I am also learning Python.