Last active
August 29, 2015 14:13
-
-
Save dex4er/a3e90ecfd22578f0163f to your computer and use it in GitHub Desktop.
Portable bytes and unicode for Python 2.x and 3.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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