pythonencodedecode_python encode decode

Python encode()

encode() 方法以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。

写法:

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

参数

encoding -- 要使用的编码,如"UTF-8"。

errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

返回值:该方法返回编码后的字符串。

Python decode()

decode() 方法以 encoding 指定的编码格式解码字符串。默认编码为字符串编码。

写法:

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

参数

encoding -- 要使用的编码,如"UTF-8"。

errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

返回值:该方法返回解码后的字符串。

实例

以下实例展示了decode()方法的实例:

实例(Python 3.7)

>>> aa="abcdfsdf"

>>> ab=aa.encode(encoding='utf-8')

>>> print(ab)

b'abcdfsdf'

>>> print(ab.decode(encoding='utf-8'))

abcdfsdf

>>>

import base64

str = "this is string examlkidiple....wow!!!";

str = base64.b64encode(bytes(str,'utf-8'))

print ("Encoded String: " , str)

print ("Decoded String: " ,base64.b64decode(str))

s=b'More\xe6\x9b\xb4\xe5\xa4\x9a\xe8\xaf\xb7\xe5\x85\xb3\xe6\xb3\xa8\xe6\x88\x91'

print(s.decode('utf-8'))

#乱码来自s.encode('gbk').decode('ISO-8859-1')

s='More¸ü¶àÇë¹Ø×¢ÎÒ'.encode('ISO-8859-1').decode('gbk')

print(s)

结果:

Encoded String: b'dGhpcyBpcyBzdHJpbmcgZXhhbWxraWRpcGxlLi4uLndvdyEhIQ=='

Decoded String: b'this is string examlkidiple....wow!!!'

More更多请关注我

More更多请关注我

>>>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值