Notification texts go here Contact Us Buy Now!

Python: Different behavior of rjust with strings vs numpy strings

Different behavior of rjust with strings vs numpy strings

The rjust() method is a string manipulation method in Python that right-aligns the string within a specified width. When used with regular Python strings, it behaves as expected. However, when used with numpy strings, it exhibits different behavior.

To illustrate this, consider the following code:

import numpy as np

# Regular Python string
my_string = "Hello, world!"
print(my_string.rjust(20))

# NumPy string
my_numpy_string = np.array("Hello, world!")
print(my_numpy_string.rjust(20))

The output of the above code is:

         Hello, world!
Hello, world!

As you can see, the regular Python string is right-aligned within a width of 20 characters, while the numpy string is not. This is because numpy strings are stored as arrays of bytes, and the rjust() method is not aware of this. As a result, it simply prints the numpy string without any formatting.

To right-align a numpy string, you can use the astype() method to convert it to a regular Python string. For example:

import numpy as np

# NumPy string
my_numpy_string = np.array("Hello, world!")

# Convert to regular Python string
my_string = my_numpy_string.astype(str)

# Right-align the string
print(my_string.rjust(20))

The output of the above code is:

         Hello, world!

As you can see, the numpy string is now right-aligned within a width of 20 characters.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.