w3resource

NumPy: Encode all the elements of a given array in cp500 and decode it again

NumPy String: Exercise-6 with Solution

Write a NumPy program to encode all the elements of a given array in cp500 and decode it again.

Sample Solution:

Python Code:

# Importing necessary library
import numpy as np

# Creating a NumPy array containing strings
x = np.array(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str)

# Displaying the original array
print("Original Array:")
print(x)

# Encoding the strings in the array using 'cp500' encoding
encoded_char = np.char.encode(x, 'cp500')

# Decoding the encoded strings using 'cp500' encoding
decoded_char = np.char.decode(encoded_char, 'cp500')

# Displaying the encoded and decoded strings
print("\nencoded =", encoded_char)
print("decoded =", decoded_char) 

Sample Input:

(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str)

Sample Output:

encoded = [b'\x97\xa8\xa3\x88\x96\x95@\x85\xa7\x85\x99\x83\x89\xa2\x85\xa2'
 b'\xd7\xc8\xd7' b'\x91\x81\xa5\x81' b'\xc3NN']
decoded = ['python exercises' 'PHP' 'java' 'C++']

Explanation:

In the above exercise –

x1 = np.array(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str): This line creates a 1-dimensional NumPy array x1 with 4 elements of string data type. The elements are ' python exercises ', 'PHP', 'Java', and 'C++'.

encoded_char = np.char.encode(x, 'cp500'): This line encodes the given strings in x into bytes using the cp500 encoding. The resulting encoded byte string is stored in the encoded_char variable.

decoded_char = np.char.decode(encoded_char,'cp500'): This line decodes the previously encoded byte string using the same cp500 encoding. The resulting decoded string is stored in the decoded_char variable.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to insert a space between characters of all the elements of a given array.
Next: Write a NumPy program to remove the leading and trailing whitespaces of all the elements of a given array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-string-exercise-6.php