NumPy strings.rjust()

The numpy.strings.rjust() function returns an array where each string is right-justified within a string of a specified length. The function optionally allows a custom fill character instead of the default space.

Syntax

</>
Copy
numpy.strings.rjust(a, width, fillchar=' ')

Parameters

ParameterTypeDescription
aarray-like (StringDType, bytes_, or str_ dtype)The input array containing strings to be right-justified.
widtharray_like (integer dtype)The length of the resulting strings. If width is less than the original string length, the string remains unchanged.
fillchararray-like (StringDType, bytes_, or str_ dtype)Optional character used for padding. The default is a space.

Return Value

Returns an array where each string is right-justified to the specified width. The output type matches the input type.


Examples

1. Right-Justifying Strings with Spaces

In this example, we right-justify each string to a length of 10 using spaces as padding.

</>
Copy
import numpy as np

# Define an array of strings
fruits = np.array(['apple', 'banana', 'cherry'], dtype='U10')

# Right-justify the strings with spaces
result = np.strings.rjust(fruits, 10)

# Print the result
print(result)

Output:

['     apple' '    banana' '    cherry']

2. Right-Justifying Strings with a Custom Fill Character

Instead of spaces, we use asterisks (*) as the padding character.

</>
Copy
import numpy as np

# Define an array of strings
fruits = np.array(['apple', 'banana', 'cherry'], dtype='U10')

# Right-justify with '*' as the padding character
result = np.strings.rjust(fruits, 10, fillchar='*')

# Print the result
print(result)

Output:

['*****apple' '****banana' '****cherry']

3. Right-Justifying When Width is Smaller than String Length

If the specified width is smaller than the length of the string, the original string remains unchanged.

</>
Copy
import numpy as np

# Define an array of strings
fruits = np.array(['apple', 'banana', 'cherry'], dtype='U10')

# Attempt to right-justify with a smaller width than the string length
result = np.strings.rjust(fruits, 4)

# Print the result
print(result)

Output:

['apple' 'banana' 'cherry']

4. Right-Justifying a Mixed-Length String Array

When different string lengths exist in an array, all elements are right-justified to the same width.

</>
Copy
import numpy as np

# Define an array of strings with varying lengths
fruits = np.array(['kiwi', 'mango', 'watermelon'], dtype='U15')

# Right-justify to a width of 15 using '-'
result = np.strings.rjust(fruits, 15, fillchar='-')

# Print the result
print(result)

Output:

['-----------kiwi' '----------mango' '-----watermelon']

The function ensures that all strings are right-aligned by filling the empty space with the specified character.