ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python中encode()函数的用法

2019-06-28 20:04:28  阅读:387  来源: 互联网

标签:编码 gb2312 python str2 str1 gbk 用法 encode cp936


encode()函数
描述:以指定的编码格式编码字符串,默认编码为 'utf-8'。

语法:str.encode(encoding='utf-8', errors='strict')     -> bytes (获得bytes类型对象)

encoding 参数可选,即要使用的编码,默认编码为 'utf-8'。字符串编码常用类型有:utf-8,gb2312,cp936,gbk等。
errors 参数可选,设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeEncodeError。 其它可能值有 'ignore', 'replace', 'xmlcharrefreplace'以及通过 codecs.register_error() 注册其它的值。
程序示例:

>>>str1 = "我爱祖国"
>>>str2 = "I love my country"
>>>str1_utf8 = str1.encode(encoding="utf-8", errors="strict")
>>>str2_utf8 = str2.encode(encoding="utf-8", errors="strict")
>>>print("utf-8编码:", str1_utf8)
utf-8编码: b'\xe6\x88\x91\xe7\x88\xb1\xe7\xa5\x96\xe5\x9b\xbd'
>>>print("utf-8编码:", str2_utf8)
utf-8编码: b'I love my country'
>>>str1_gb2312 = str1.encode(encoding="gb2312", errors="strict")
>>>str2_gb2312 = str2.encode(encoding="gb2312", errors="strict")
>>>print("gb2312编码:", str1_gb2312)
gb2312编码: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
>>>print("gb2312编码:", str2_gb2312)
gb2312编码: b'I love my country'
>>>str1_cp936 = str1.encode(encoding="cp936", errors="strict")
>>>str2_cp936 = str2.encode(encoding="cp936", errors="strict")
>>>print("cp936编码:", str1_cp936)
cp936编码: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
>>>print("cp936编码:", str2_cp936)
cp936编码: b'I love my country'
>>>str1_gbk = str1.encode(encoding="gbk", errors="strict")
>>>str2_gbk = str2.encode(encoding="gbk", errors="strict")
>>>print("gbk编码:", str1_gbk)
gbk编码: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
>>>print("gbk编码:", str2_gbk)
gbk编码: b'I love my country'
>>>str1_utf8.decode('utf-8')
'我爱祖国'
>>>str1_gb2312.decode("gb2312")
'我爱祖国'
>>>str1_cp936.decode("cp936")
'我爱祖国'
>>>str1_gbk.decode("gbk")
'我爱祖国'
>>>str2_utf8.decode("utf-8")
'I love my country'

原文:https://blog.csdn.net/qq_40678222/article/details/83033492 

版权声明:本文为博主原创文章,转载请附上博文链接!

标签:编码,gb2312,python,str2,str1,gbk,用法,encode,cp936
来源: https://www.cnblogs.com/ilyou2049/p/11104517.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有