2

I would like to covert a numpy uint8 array to string in python

import numpy as np
arr = np.array([98, 111,111,107])
print(arr.view('c')) # I can see the output [b'b' b'' b'o' b'' b'o' b'' b'k' b'']

I would like to get book ? Any pointer?

2 Answers 2

1

The main problem you're facing is that you don't have an array of UInt8, you have an array of Int64, so when you view it as a character array you get a lot of extraneous data.

If you correct set your dtype, you can view this appropriately.

arr = np.array([98, 111,111,107], dtype=np.uint8)
arr.view(f'S{arr.shape[0]}')

# array([b'book'], dtype='|S4')
Sign up to request clarification or add additional context in comments.

Comments

1
string_ = [chr(i) for i in arr] # outputs: ['b', 'o', 'o', 'k']

Then,

string_ = ''.join(string_) # outputs: 'book'

Comments

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.