I. Difference between bytes and string
bytes is also called a sequence of bytes, not characters. It can take values in the range 0 <= bytes <= 255, and will be output with the character b at the top; string is a string type in python.
Primarily for in-computers, string is primarily for people;
After encoding encode, transformed into a binary object to the computer to identify; bytes after decoding decode, transformed into a string, so that we can see, but note that the reverse encoding of the encoding rules are a range, \xc8 is not the range of utf8 recognition;
if __name__ == "__main__": # Byte objectsb b = b"" # String object s s = "" print(b) print(type(b)) print(s) print(type(s))
Output results:
b''
<class 'bytes'>
<class 'str'>
II.bytes to string
The string is encoded into bytes.
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:What can I do to help you? @Blog(Personal Blog Address): @WeChat Official Account(WeChat Public):apes saypython @Github: @File:python_bytes_string.py @Time:2020/2/26 21:25 @Motto:short steps don't make a big step,You can't make a river or an ocean without accumulating small streams.,The excitement of the program life needs to be built up persistently.! """ if __name__ == "__main__": s = "" # Convert strings to byte objects b2 = bytes(s, encoding='utf8') # Coding format must be developed # print(b2) # String encode will get a bytes object b3 = (s) b4 = () print(b3) print(type(b3)) print(b4) print(type(b4))
Output results:
b''
<class 'bytes'>
b''
<class 'bytes'>
III.string to bytes
Bytes are decoded and converted to string.
if __name__ == "__main__": # Byte objectsb b = b"" print(b) b = bytes("Ape says python.", encoding='utf8') print(b) s2 = (b) s3 = () print(s2) print(s3)
Output results:
b''
b'\xe7\x8c\xbf\xe8\xaf\xb4python'
Ape says python
Ape says python
This is the whole content of this article.