The encode() function is used to encode the input string. The set of available codecs are taken from the Python standard library.
This function calls the str.encode in an element-wise manner.
The default encoding scheme used is utf_8.
Syntax of encode():
The syntax required to use this function is as follows:
numpy.char.encode(a, encoding=None, errors=None)
The above syntax indicates that encode() is a function of the char module and takes three paameters.
Parameters:
Let us discuss the parameters of this function:
- a This parameter indicates an array of strings
- encoding This is an optional parameter that denotes the name of the encoding to be used.
- errors This parameter is used to specify how to handle encoding errors.
Returned Values:
The encode() function will always return an encoded string.
Example 1:
The code snippet is as follows where we will use encode() function with some different encoding, say cp037:
import numpy as np
a = ['aAaAaA', ' aA ', 'abBABba','dffgs','ttsred']
print("Input is:")
print(a)
x = np.char.encode(a, encoding='cp037', errors=None)
print("Encoded String is:")
print(x)
Output:
Input is: ['aAaAaA', ' aA ', 'abBABba', 'dffgs', 'ttsred'] Encoded String is: [b'\x81\xc1\x81\xc1\x81\xc1' b'@@\x81\xc1@@' b'\x81\x82\xc2\xc1\xc2\x82\x81' b'\x84\x86\x86\x87\xa2' b'\xa3\xa3\xa2\x99\x85\x84']
Example 2:
In the example given below, we will use encoding scheme utf-8 and will check the output:
import numpy as np
a = ['aAaAaA', ' aA ', 'abBABba','dffgs','ttsred']
print("Input is:")
print(a)
x = np.char.encode(a, encoding='utf-8', errors=None)
print("Encoded String is:")
print(x)
Output:
Input is: ['aAaAaA', ' aA ', 'abBABba', 'dffgs', 'ttsred'] Encoded String is: [b'aAaAaA' b' aA ' b'abBABba' b'dffgs' b'ttsred']
