7

I have string

my_string = "My name is Aman Raparia"

which I converted to numpy array of ordinal values using the statement

my_string_numpy_array = np.fromstring(my_string, dtype=np.uint8)

Is there any way to get back the original string from the my_string_numpy_array?

3
  • Did either of the posted solutions work for you? Commented Jun 26, 2017 at 8:23
  • Hello @Divaker yes your solution perfectly worked for me. Commented Jun 28, 2017 at 7:44
  • np.fromstring() is now deprecated, the question for the recommended np.frombuffer() would be: my_string = b"My name is Aman Raparia" my_string_numpy_array = np.frombuffer(my_string, dtype=np.uint8). My EDIT to add this new information to the question was rejected. Commented Nov 23, 2020 at 8:27

3 Answers 3

7

Use ndarray.tostring -

my_string_numpy_array.tostring()

Sample output -

In [176]: my_string_numpy_array.tostring()
Out[176]: 'My name is Aman Raparia'
Sign up to request clarification or add additional context in comments.

Comments

2

The right answer for is Divakar's ndarray.tostring.

An alternative is to use chr on each array element and join together (for a non numpy array for example):

>>> ''.join([chr(e) for e in my_string_numpy_array])
'My name is Aman Raparia'

Comments

1

Now some years later, np.fromstring() is deprecated:

my_string_numpy_array = np.fromstring(my_string, dtype=np.uint8) :1: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead

Use np.frombuffer() instead. And switch back to the input with np.array2string().

import numpy as np

my_string = b"My name is Aman Raparia"
my_string_numpy_array = np.frombuffer(my_string, dtype=np.uint8)
np.array2string(my_string_numpy_array, formatter={'int':lambda x: chr(x).encode()}, separator='').strip('[]').encode()

Out: b'My name is Aman Raparia'

You can drop the .encode() to get string directly. It is just added to get to the original input again, and np.frombuffer() requires a byte formatted buffer.

If you have more than one item as output and then need to remove the []-brackets, see np.array2string not removing brackets around an array.

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.