NumPy: Encode all the elements of a given array in cp500 and decode it again
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics