python 编码处理

Description:

This method decodes the string using the codec registered forencoding. encoding defaults to the default string encoding.

Syntax:

str.decode(encoding='UTF-8',errors='strict')

Parameters:

Here is the detail of parameters:

  • encoding: is the encodings to be used. For a list of all encoding schemes please visit:Standard Encodings.

  • errors : may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error().

Return Value:

It returns an decoded version of the stri

Example:

#!/usr/bin/python

str = "this is string example....wow!!!";
str = str.encode('base64','strict');

print "Encoded String: " + str;
print "Decoded String: " + str.decode('base64','strict')

This will produce following result:

Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=

Decoded String: this is string example....wow!!!



bytes 对象有
一个 decode()方法,它使用某种字符编码作为参数,然后依照
这种编码方式将 bytes 对象转换为字符串,对应地,字符串有
一个 encode()方法,它也使用某种字符编码作为参数,然后依
照它将串转换为 bytes 对象。在上一个例子中,解码的过程相
对直观一些 — 使用 ASCII 编码将一个字节序列转换为字符
串。同样的过程对其他的编码方式依然有效 — 传统的(非
Unicode)编码方式也可以,只要它们能够编码串中的所有字
符。  
>>> a_string = '深入 Python'         1
>>> len(a_string)
9
>>> by = a_string.encode('utf‐8')    2
>>> by
b'\xe6\xb7\xb1\xe5\x85\xa5 Python'
>>> len(by)
13
>>> by = a_string.encode('gb18030')  3
>>> by
b'\xc9\xee\xc8\xeb Python'
>>> len(by)
11
>>> by = a_string.encode('big5')     4
>>> by
b'\xb2`\xa4J Python'
>>> len(by)
11
>>> roundtrip = by.decode('big5')    5
>>> roundtrip
'深入 Python'
>>> a_string == roundtrip
True
1. a_string 是一个字符串。它有 9 个字符。  
2. by 是一个 bytes 对象。它有 13 个字节。它是通过 a_string
使用 UTF‐8 编码而得到的一串字节序列。  
3.
by还是一个bytes对象。它有 11 个字节。它是通过a_string
使用GB18030编码而得到的一串字节序列。  
4.
此时的by仍旧是一个bytes对象,由 11 个字节组成。它又是
一种完全不同的字节序列,我们通过对a_string使用Big5编码
得到。  
5.
roundtrip 是一个字符串,共有 9 个字符。它是通过对 by 使
用 Big5 解码算法得到的一个字符序列。并且,从执行结果可
以看出,roundtrip 与 a_string 是完全一样的。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值