python string字符串函数

python decode()函数 以 encoding 指定的编码格式解码字符串,默认编码为字符串编码。

语法

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

参数

  • encoding:要使用的编码,如:utf-8,gb2312,cp936,gbk等。

  • errors:设置不同解码错误的处理方案。默认为 'strict',意为编码错误引起一个 UnicodeDecodeError。 其它可能得值有 'ignore', 'replace'以及通过 codecs.register_error() 注册的1其它值。

返回值

返回解码后的字符串

程序示例

#!/usr/bin/python
# coding=utf-8
s = "我爱祖国"
str1 = s.encode(encoding="utf-8",errors="strict")
str2 = s.encode("gb2312") #编码错误的处理方案默认为"strict"
str3 = s.encode("gbk")
print(str1.decode(encoding="utf-8",errors="strict"))#用utf-8的解码格式,解码str1.
print(str1.decode(encoding="gbk",errors="ignore"))##如果以gbk的解码格式对str1进行解码得,将无法还原原来的字符串内容
print(str1.decode(encoding="gbk",errors="strict"))
print(str1.decode(encoding="gbk",errors="replace"))
print("\n")
print(str2.decode("gb2312"))
print(str3.decode("gbk")) 

程序运行结果:

我爱祖国
鎴戠埍绁栧浗
鎴戠埍绁栧浗
鎴戠埍绁栧浗


我爱祖国
我爱祖国

注:在python3.x中,encode()函数只能用于字符串类型,而decode()函数只能用于字节数据类型。

程序示例中 str1,str2,str3都是字节数据类型(通过encode()函数把 字符串类型s 转换为字节数据类型)。