python3 bytes().py

江枫思渺然 提交于 2020-02-04 11:05:29
"""
python3 bytes().py
参考:https://blog.csdn.net/weixin_40283816/article/details/83591582
知识点:
1.str to bytes
str.encode()  -> bytes
bytes(str, encoding="utf8")  -> bytes

2. bytes -> str
str(bytes, encoding="utf8")  -> str
bytes.decode()  -> str
"""
# 1.
print("1.")
b = b"example"  # bytes object
print('b:', b)
# b: b'example'
print(type(b))
# <class 'bytes'>


# 2.
print("2.")
s = "example"  # str object
sb = bytes(s, encoding="utf8")  # str to bytes
print("sb:", sb)
# sb: b'example'
print(type(sb))
# <class 'bytes'>

sb = str.encode(s)  # str to bytes
print("sb:", sb)
# sb: b'example'
print(type(sb))
# <class 'bytes'>

# 3.
print("3.")
bs = str(b, encoding="utf8")  # bytes to str
print("bs:", bs)
# bs: example
print(type(bs))
# <class 'str'>
bs = bytes.decode(b)  # bytes to str
bs = b.decode()
print("bs:", bs)
# bs: example
print(type(bs))
# <class 'str'>

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!