Created
September 23, 2009 20:56
-
-
Save andreisavu/192270 to your computer and use it in GitHub Desktop.
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
# 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