- In Python 3, bytes contains sequences of 8 bit values, str contains sequences of Unicode characters. bytes and str instances cannot be used together with operators such as < or +
Effective Python
Helper function to ensure str or bytes
def to_str(bytes_or_str):
if instance(bytes_or_str, bytes):
value = bytes_ot_str.decode('utf-8')
else:
value = bytes_or_str
return value
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str).encode('utf-8')
else:
value = bytes_or_str
return value
Recommended Posts