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?
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
Let us see how to save a numpy array to a text file. Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function.
The elements of a NumPy array, or simply an array, are usually numbers, but can also be boolians, strings, or other objects.
Use ndarray.tostring
-
my_string_numpy_array.tostring()
Sample output -
In [176]: my_string_numpy_array.tostring()
Out[176]: 'My name is Aman Raparia'
The right answer for numpy 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'
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