Pavan K
Pavan K

Reputation: 4693

Convert numpy uint8 array to string

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?

Upvotes: 2

Views: 4385

Answers (2)

user3483203
user3483203

Reputation: 51165

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')

Upvotes: 1

shuvo
shuvo

Reputation: 1956

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

Then,

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

Upvotes: 1

Related Questions