Skip to content

Instantly share code, notes, and snippets.

@nenetto
Created September 26, 2023 06:29
Show Gist options
  • Save nenetto/7beaaa00f8218e495414a04d74f444a5 to your computer and use it in GitHub Desktop.
Save nenetto/7beaaa00f8218e495414a04d74f444a5 to your computer and use it in GitHub Desktop.
Python bytes, string and unicode
def to_str(bytes_or_str):
"""Transform to string UTF-8"""
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode(‘utf-8’)
else:
value = bytes_or_str
return value # Instance of str
def to_bytes(bytes_or_str):
"""Transform to bytestring"""
if isinstance(bytes_or_str, str):
value = bytes_or_str.encode(‘utf-8’)
else:
value = bytes_or_str
return value # Instance of bytes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment