python3 str.encode()_bytes.decode().py

"""
python3 str1.encode()_bytes.decode().py
参考:https://www.runoob.com/python3/python3-string-encode.html
知识点:
1.
str1.encode(encoding='UTF-8',errors='strict') -> bytes 对象。
encode() 方法以指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。
encoding -- 要使用的编码,如: UTF-8。
errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。
其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace'
以及通过 codecs.register_error() 注册的任何值。
该方法返回编码后的字符串,它是一个 bytes 对象。
2.

"""
str1 = "菜鸟教程"
print(str1)
# 菜鸟教程
print(type(str1))
# <class 'str'>

bytes_utf8 = str1.encode("UTF-8")
bytes_gbk = str1.encode("GBK")
print("bytes_utf8:", bytes_utf8)
# bytes_utf8: b'\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'
print("bytes_gbk:", bytes_gbk)
# bytes_gbk: b'\xb2\xcb\xc4\xf1\xbd\xcc\xb3\xcc'
print(type(bytes_utf8), type(bytes_gbk))
# <class 'bytes'> <class 'bytes'>

print("UTF-8 解码:", bytes_utf8.decode('UTF-8', 'strict'))
print("GBK 解码:", bytes_gbk.decode('GBK', 'strict'))
# UTF-8 解码: 菜鸟教程
# GBK 解码: 菜鸟教程


发布了198 篇原创文章 · 获赞 58 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/weixin_42193179/article/details/103726104