I have a numpy array X
with dtype 'S' (numpy.bytes_)
. For example printing print(X[0, 0])
yields b'somestring'
. Similarly str(X[0, 0])
returns string "b'somestring'"
.
However I need to print or convert to string so that it does not contain b'
at the beginning and '
at the end. I just want to print somestring
or return a string "somestring"
. How to do it?
Note: I cannot change the type of the array.
Using the decode() method Python provides the built-in decode() method, which is used to convert bytes to a string. Let's understand the following example.
Similarly, Decoding is process to convert a Byte object to String. It is implemented using decode() . A byte string can be decoded back into a character string, if you know which encoding was used to encode it.
You just need to decode the string back into ASCII, so it would just be:
bytes_string.decode('UTF-8')
Demo:
>>> b'somestring'.decode('UTF-8') 'somestring'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With