Skip to content

Instantly share code, notes, and snippets.

@dex4er
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dex4er/a3e90ecfd22578f0163f to your computer and use it in GitHub Desktop.
Save dex4er/a3e90ecfd22578f0163f to your computer and use it in GitHub Desktop.
Portable bytes and unicode for Python 2.x and 3.x
import sys
DEFAULT_CHARSET = 'utf-8'
if sys.version_info >= (3, 0):
def b(string, charset=DEFAULT_CHARSET):
if isbytes(string):
return bytes(string)
else:
return bytes(str(string), charset)
else:
def b(string, charset=DEFAULT_CHARSET):
if isinstance(string, unicode):
return string.encode(charset)
else:
return str(string)
if sys.version_info >= (3, 0):
def u(string, charset=DEFAULT_CHARSET):
if isbytes(string):
return string.decode(charset)
else:
return str(string)
else:
def u(string, charset=DEFAULT_CHARSET):
if isinstance(string, unicode):
return string
elif hasattr(string, '__unicode__'):
return unicode(string)
else:
return str(string).decode(charset)
def isbytes(obj):
return isinstance(obj, bytes) and not isinstance(obj, str)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment