Python numpy.char.center() Method (With Examples)

By IncludeHelp Last updated : December 1, 2023

Python numpy.char.center() Method

The center() method is a built-in method of the char class in the numpy module, it returns an array with its elements centered in a string of a given length. This method requires three parameters one is an array and second one is width and the third one is the fill character which is optional.

Module

The following module is required to use the center() method:

import numpy as np

Syntax

The following is the syntax of the center() method:

char.center(arr, width, fill_character = ' ')

Parameter(s)

The following are the parameter(s):

  • arr: An array of strings or Unicode.
  • width: An integer value that will be the length of the resulting string.
  • fill_character: A string or Unicode type, which is used for padding the elements of an array. It's an optional parameter having space as its default value.

Return Value

The return type of the center() method is <class 'numpy.ndarray'>, it returns an updated array after performing the element-wise string formatting.

Example 1: Applying char.center() method on a string

# Importing numpy module
import numpy as np

# Creatung variables for string, width, & fill_character
arr = "Hello"
width = 8
fill_character = "#"

# Using char.center() method
result = np.char.center(arr, width, fill_character)

# Printing the result
print("\nThe result is:", result)
print("\nThe type of the result is:", type(result))

Output

The output of the above example is:

The result is: #Hello##

The type of the result is: <class 'numpy.ndarray'>

Example 2: Applying char.center() method on an array of strings

# Importing numpy module
import numpy as np

# Creatung variables for array of strings, width, & fill_character
arr = ["Hello", "World", "How're You?"]
width = 15
fill_character = "*"

# Using char.center() method
result = np.char.center(arr, width, fill_character)

# Printing the result
print("\nThe result is:", result)
print("\nThe type of the result is:", type(result))

Output

The output of the above example is:

The result is: ['*****Hello*****' '*****World*****' "**How're You?**"]

The type of the result is: <class 'numpy.ndarray'>

Example 3: Applying char.center() method on an array of strings w/o using fill_character parameter

# Importing numpy module
import numpy as np
 
# Creatung variables for array of strings, width
arr = ["Hello", "World", "How're You?"]
width = 15
 
# Using char.center() method
result = np.char.center(arr, width)
 
# Printing the result
print("\nThe result is:", result)
print("\nThe type of the result is:", type(result))

Output

The output of the above example is:

The result is: ['     Hello     ' '     World     ' "  How're You?  "]

The type of the result is: <class 'numpy.ndarray'>

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.