Numpy char.center() Function



The Numpy char.center() function which is used to center the elements of an array of strings. This function pads the strings with a specified character to a given width so the original string is centered within the new string of the specified width.

This function takes the parameters namely, input array, width and fillchar.

This function is useful for formatting strings to align them visually within a specific width which can be particularly handy for creating tables or aligned text outputs.

Syntax

Following is the syntax of Numpy char.center() function −

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

Parameters

Below are the parameters of the Numpy char.center() function −

  • a(array_like): This is the total width of the resulting string. If the specified width is less than or equal to the length of the original string, no padding is added.

  • width(int): An integer specifying how many times to repeat each string in the array.

  • fillchar(str, optional): The character used to pad the string. The default value is a space (' ').

Return Value

This function returns an array of the same shape as input array, with each element being a centered version of the corresponding element in the input array.

Example 1

Following is the basic example of Numpy char.center() function. Here in this example we are taking the fillchar parameter with the default value (' ') −

import numpy as np

# Define an array of strings
a = np.array(['cat', 'dog', 'elephant'])

# Center each string in a field of width 10, using spaces as the fill character
result = np.char.center(a, 10)
print(result)

Below is the output of the basic example of numpy.char.center() function −

['   cat    ' '   dog    ' ' elephant ']

Example 2

Here in this example we'll show how to use char.center() function to center strings within a specified width using a different fill character instead of the default space. This can be useful for formatting strings in a visually distinct manner −

import numpy as np

# Define an array of strings
a = np.array(['cat', 'dog', 'elephant'])

# Center each string in a field of width 10, using '*' as the fill character
result = np.char.center(a, 10, fillchar='*')
print(result)

Here is the output of the above example −

['***cat****' '***dog****' '*elephant*']

Example 3

Here is an example which shows how to center a single string in an array with a specified width and a custom fill character −

import numpy as np

# Define a single string
a = np.array(['hello'])

# Center the string in a field of width 11, using '-' as the fill character
result = np.char.center(a, 11, fillchar='-')
print(result)

Below is the output of centering the single string −

['---hello---']
numpy_string_functions.htm
Advertisements