Common python tools-small functions-character type conversion, common python tools
Python3 has two types of character sequences: bytes and str. The former instance contains the original 8-bit value of the byte, each of which has 8 binary digits; the latter instance contains Unicode characters. The most common encoding method for converting Unicode characters to binary data is the UTF-8, which must use the encode method; the decode method must be used to convert binary data to Unicode characters.
In actual development, we often need to convert the two types of characters. Therefore, we need to write two auxiliary functions to convert the two types of characters, this allows the converted input data to meet our expectations.
1. Accept str or bytes and always return the 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. the method that accepts str or bytes and always returns 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