Python字符串encode()
Python字符串encode()函数用于使用提供的编码对字符串进行编码。此函数返回bytes对象。如果我们不提供编码,将使用“utf-8”编码作为默认值。
Python字节decode()
Python字节decode()函数用于将字节转换为字符串对象。这两个函数都允许我们指定用于处理编码/解码错误的错误处理方案。默认值是’strict’,表示编码错误会引发UnicodeEncodeError。其他可能的值包括’ignore’、’replace’和’xmlcharrefreplace’。让我们看一个简单的例子,演示Python字符串encode()和decode()函数的用法。
str_original = 'Hello'
bytes_encoded = str_original.encode(encoding='utf-8')
print(type(bytes_encoded))
str_decoded = bytes_encoded.decode()
print(type(str_decoded))
print('Encoded bytes =', bytes_encoded)
print('Decoded String =', str_decoded)
print('str_original equals str_decoded =', str_original == str_decoded)
输出:
<class 'bytes'>
<class 'str'>
Encoded bytes = b'Hello'
Decoded String = Hello
str_original equals str_decoded = True
上面的例子并未清楚地演示编码的用法。让我们看另一个例子,我们将从用户那里获取输入,然后对其进行编码。输入字符串中将包含一些特殊字符。
str_original = input('Please enter string data:\n')
bytes_encoded = str_original.encode()
str_decoded = bytes_encoded.decode()
print('Encoded bytes =', bytes_encoded)
print('Decoded String =', str_decoded)
print('str_original equals str_decoded =', str_original == str_decoded)
输出:
Please enter string data:
aåb∫cçd∂e´´´ƒg©1¡
Encoded bytes = b'a\xc3\xa5b\xe2\x88\xabc\xc3\xa7d\xe2\x88\x82e\xc2\xb4\xc2\xb4\xc2\xb4\xc6\x92g\xc2\xa91\xc2\xa1'
Decoded String = aåb∫cçd∂e´´´ƒg©1¡
str_original equals str_decoded = True
您可以从我们的 GitHub 代码库中查看完整的 Python 脚本和更多 Python 示例。
Source:
https://www.digitalocean.com/community/tutorials/python-string-encode-decode