python中encode()函数的用法
作者:互联网
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