使用 encode()
函数与不同的编码方案
我们现在将使用 encode()
函数与两种不同的编码方案 'cp037' 和 'utf-8'。为此,我们首先定义一个字符串数组。
a = ['aAaAaA', ' aA ', 'abBABba','dffgs','ttsred']
使用编码方案 'cp037':
我们通过传递输入数组和编码类型作为参数,使用 encode()
函数与编码方案 'cp037'。以下是代码块:
x = np.char.encode(a, encoding='cp037', errors=None)
上述代码块读取输入数组 a
并使用 'cp037' 编码方案对其进行编码。编码后的字符串存储在变量 x
中。由于未指定错误处理机制,errors
参数设置为 None
。我们现在打印输入数组和编码后的字符串如下:
print("Input is:")
print(a)
print("Encoded String is:")
print(x)
输出:
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']
使用编码方案 'utf-8':
我们通过传递输入数组和编码类型作为参数,使用 encode()
函数与编码方案 'utf-8'。以下是代码块:
x = np.char.encode(a, encoding='utf-8', errors=None)
上述代码块读取输入数组 a
并使用 'utf-8' 编码方案对其进行编码。编码后的字符串存储在变量 x
中。由于未指定错误处理机制,errors
参数设置为 None
。我们现在打印输入数组和编码后的字符串如下:
print("Input is:")
print(a)
print("Encoded String is:")
print(x)
输出:
Input is:
['aAaAaA', ' aA ', 'abBABba', 'dffgs', 'ttsred']
Encoded String is:
[b'aAaAaA' b' aA ' b'abBABba' b'dffgs' b'ttsred']