There are two types of Python3 that represent the sequence of characters: bytes and str. An instance of the former contains bytes with the original 8-bit value, 8 bits per byte, and an instance of the latter containing Unicode characters. The most common encoding for turning Unicode characters into binary data is UTF-8, which must use the Encode method; The Decode method must be used to turn binary data into Unicode characters.
In actual development we often need to convert between these two character types, so we need to write two auxiliary functions to convert between these two situations, so that the converted input data can meet our expectations.
1, accept Str or bytes, and always return str method:
def to_str (str_or_bytes):
If Isinstance (str_or_bytes,bytes):
Value = Str_or_bytes.decode (' Utf-8 ')
Else
Value = Str_or_bytes
return value
2, accept Str or bytes, and always return the method of bytes:
def to_bytes (str_or_bytes):
If Isinstance (STR_OR_BYTES,STR):
Value = Str_or_bytes.encode (' Utf-8 ')
Else
Value = Str_or_bytes
return value
Python Common tools small function-character type conversion