c# url encode编码转换_一日一技:python中的string.encode()方法

ef639c123c1a65647197f4f5d4354db3.png

string.encode()方法

string.encode()方法返回给定字符串的编码形式,

从Python 3.0开始,字符串以Unicode格式存储,即字符串中的每个字符都由一个代码点表示。 因此,每个字符串只是Unicode代码点的序列。

为了有效地存储这些字符串,将代码点的顺序转换为字节集, 该过程称为编码。

存在各种不同的编码,它们对字符串的处理不同。 流行的编码是utf-8,ascii等。

使用string.encode()方法,我们可以将未编码的字符串转换为Python支持的任何编码。 默认情况下,Python使用utf-8编码。


encode()方法的语法为:

string.encode(encoding='UTF-8',errors='strict')

string.encode()参数

默认情况下,encode()方法不需要任何参数。


string.encode(),它返回字符串的utf-8编码形式。如果编码失败,将引发UnicodeDecodeError异常。

它有两个参数:

  1. encoding-字符串必须是可编码的类型.
  2. errors-编码失败时的响应。错误响应有以下六种类型:
  • strict-默认响应,失败时会引发UnicodeDecodeError异常
  • ignore-从结果中忽略无法编码的unicode
  • replace-将无法编码的Unicode替换为问号?
  • xmlcharrefreplace-插入XML字符引用而不是无法编码的unicode
  • backslashreplace-插入 uNNNN转义序列,而不是无法编码的unicode
  • namereplace-插入 N {...}转义序列,而不是无法编码的unicode

下面,我们直接来用代码实例演示如下:

示例1:编码为默认的Utf-8编码

string = 'pythön!'print('The string is:', string)string_utf = string.encode()print('The encoded version is:', string_utf)

输出:

The string is: pythön!The encoded version is: b'pythxc3xb6n!'

示例2:使用errors参数编码:

string = 'pythön!'print('The string is:', string)print('The encoded version (with ignore) is:', string.encode("ascii", "ignore"))print('The encoded version (with replace) is:', string.encode("ascii", "replace"))

输出:

The string is: pythön!The encoded version (with ignore) is: b'pythn!'The encoded version (with replace) is: b'pyth?n!'

这只是我们演示的一部分,我们还可以尝试上面其他encoding 和 error的参数。

大家可以用实例自己动手操作一下。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值