Python 字符串 encode() decode()

Python 字符串编码()

Python 字符串编码() 函数用于使用提供的编码来编码字符串. 此函数返回 byte 对象. 如果我们不提供编码,则默认使用utf-8 编码。

Python 字节解码()

Python 字节解码() 函数用于将字节转换为字节字符串对象. 这些函数都允许我们指定用于编码/解码错误的错误处理方案. 默认是严格,这意味着编码错误会引发 UnicodeEncodeError。 一些其他可能的值是忽略,取代xmlcharrefreplace。 让我们来看看 Python 字符串解码() 函数的一个简单的例子。

 1str_original = 'Hello'
 2
 3bytes_encoded = str_original.encode(encoding='utf-8')
 4print(type(bytes_encoded))
 5
 6str_decoded = bytes_encoded.decode()
 7print(type(str_decoded))
 8
 9print('Encoded bytes =', bytes_encoded)
10print('Decoded String =', str_decoded)
11print('str_original equals str_decoded =', str_original == str_decoded)

输出:

1<class 'bytes'>
2<class 'str'>
3Encoded bytes = b'Hello'
4Decoded String = Hello
5str_original equals str_decoded = True

上面的例子并不清楚地显示了编码的使用情况,让我们看看另一个例子,我们将从用户那里获得输入,然后编码它,我们将在用户输入字符串中输入一些特殊字符。

1str_original = input('Please enter string data:\n')
2
3bytes_encoded = str_original.encode()
4
5str_decoded = bytes_encoded.decode()
6
7print('Encoded bytes =', bytes_encoded)
8print('Decoded String =', str_decoded)
9print('str_original equals str_decoded =', str_original == str_decoded)

Output: python string encode decode

1Please enter string data:
2aåb∫cçd∂e´´´ƒg©1¡
3Encoded 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'
4Decoded String = aåb∫cçd∂e´´´ƒg©1¡
5str_original equals str_decoded = True

您可以从我们的 GitHub 存储库中查阅完整的 Python 脚本和更多 Python 示例。

引用: str.encode() API Doc, bytes.decode() API Doc

Published At
Categories with 技术
comments powered by Disqus