python字符串encode()decode()

Python字符串encode() (Python String encode())

Python string encode() function is used to encode the string using the provided encoding. This function returns the bytes object. If we don’t provide encoding, “utf-8” encoding is used as default.

Python字符串encoding()函数用于使用提供的编码对字符串进行编码。 此函数返回bytes对象。 如果我们不提供编码,则默认使用“ utf-8”编码。

Python字节的decode() (Python Bytes decode())

Python bytes decode() function is used to convert bytes to string object.

Python字节bytes()函数用于将字节转换为字符串对象。

Both these functions allow us to specify the error handling scheme to use for encoding/decoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Some other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’.

这两个功能使我们能够指定用于编码/解码错误的错误处理方案。 默认值为“严格”,这意味着编码错误会引发UnicodeEncodeError。 其他一些可能的值是'ignore','replace'和'xmlcharrefreplace'。

Let’s look at a simple example of python string encode() decode() functions.

我们来看一个简单的python字符串encode()encode()函数示例。

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)

Output:

输出:

<class 'bytes'>
<class 'str'>
Encoded bytes = b'Hello'
Decoded String = Hello
str_original equals str_decoded = True

Above example doesn’t clearly demonstrate the use of encoding. Let’s look at another example where we will get inputs from the user and then encode it. We will have some special characters in the input string entered by the user.

上面的示例没有清楚地说明编码的使用。 让我们看另一个示例,在该示例中,我们将从用户那里获取输入,然后对其进行编码。 用户输入的输入字符串中将包含一些特殊字符。

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)

Output:

python string encode decode

输出:

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 Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: str.encode() API Doc, bytes.decode() API Doc

参考: str.encode()API文档bytes.decode()API文档

翻译自: https://www.journaldev.com/23617/python-string-encode-decode

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值