NumPy strings.center()
The numpy.strings.center()
function returns a copy of a string with its elements centered in a string of a specified length.
Optional padding characters can be used to fill the remaining space.
Syntax
numpy.strings.center(a, width, fillchar=' ')
Parameters
Parameter | Type | Description |
---|---|---|
a | array_like (StringDType, bytes_, or str_) | The input string or array of strings to be centered. |
width | array_like (integer dtype) | The total length of the resulting string. If width is smaller than the original string length, the original string is returned unchanged. |
fillchar | array_like (StringDType, bytes_, or str_), optional | The character used for padding. Default is a space (‘ ‘). |
Return Value
Returns an ndarray containing strings that are centered within the specified width, padded using the specified character.
Examples
1. Centering a Single String with Default Padding
In this example, we center the string 'apple'
within a width of 10 characters using spaces as the default padding character.
import numpy as np
# Define the input string
fruit = np.array('apple', dtype='U')
# Center the string within a width of 10
result = np.strings.center(fruit, 10)
# Print the result
print("Centered String:", repr(result))
Output:
Centered String: array(' apple ', dtype='<U10')

2. Centering Multiple Strings in an Array
We center multiple fruit names within a width of 12 characters using space padding.
import numpy as np
# Define an array of fruit names
fruits = np.array(['apple', 'banana', 'cherry'], dtype='U')
# Center each string within a width of 12
result = np.strings.center(fruits, 12)
# Print the results
print("Centered Strings:")
print(repr(result))
Output:
Centered Strings:
array([' apple ', ' banana ', ' cherry '], dtype='<U12')

3. Using a Custom Padding Character
We use a custom character '-'
instead of spaces for padding.
import numpy as np
# Define an array of fruit names
fruits = np.array(['apple', 'banana', 'cherry'], dtype='U')
# Center each string with '-' as the padding character
result = np.strings.center(fruits, 12, fillchar='-')
# Print the results
print("Centered Strings with '-' padding:")
print(repr(result))
Output:
Centered Strings with '-' padding:
array(['---apple----', '---banana---', '---cherry---'], dtype='<U12')

4. Handling Strings Longer Than the Specified Width
If the width is smaller than the string length, the function returns the original string without modification.
import numpy as np
# Define an array of fruit names
fruits = np.array(['apple', 'banana', 'cherry'], dtype='U')
# Center each string in a smaller width
result = np.strings.center(fruits, 4)
# Print the results
print("Strings when width is smaller than the string length:")
print(repr(result))
Output:
Strings when width is smaller than the string length:
array(['apple', 'banana', 'cherry'], dtype='<U6')

Since the width is smaller than the string length, no centering is applied, and the original strings are returned.