Skip to content

Instantly share code, notes, and snippets.

@andreisavu
Created September 23, 2009 20:56
Show Gist options
  • Save andreisavu/192270 to your computer and use it in GitHub Desktop.
Save andreisavu/192270 to your computer and use it in GitHub Desktop.
# Returns a bytestring version of 's', encoded as specified in 'encoding'.
def smart_str(s, encoding='utf-8', errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
"""
if not isinstance(s, basestring):
try:
return str(s)
except UnicodeEncodeError:
return unicode(s).encode(encoding, errors)
elif isinstance(s, unicode):
return s.encode(encoding, errors)
elif s and encoding != 'utf-8':
return s.decode('utf-8', errors).encode(encoding, errors)
else:
return s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment