39

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.

1 Answer 1

50

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'
Sign up to request clarification or add additional context in comments.

2 Comments

how about a whole array and not just one element?
You could do X.astype(str), although I'm not sure exactly how this performs the decoding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.