Skip to content

Instantly share code, notes, and snippets.

@takluyver
Created October 1, 2012 18:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takluyver/3813714 to your computer and use it in GitHub Desktop.
Save takluyver/3813714 to your computer and use it in GitHub Desktop.
Make a str from any string
def utf8(string):
"""Convert any string - bytes or unicode - to a str (i.e. unicode on
Python 3, utf-8 encoded bytes on Python 2).
"""
if config.python3:
if isinstance(string, bytes):
return string.decode('utf-8') # Hope it was UTF-8 encoded!
else:
# Python 2:
if isinstance(string, unicode):
return string.encode('utf-8')
# String is already a str
return string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment