Last active
August 29, 2015 14:01
-
-
Save dawn110110/ca711e39841142256b57 to your computer and use it in GitHub Desktop.
Safe unicode function(modified from web.py)
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
def safeunicode(obj, encoding='utf-8'): | |
r"""s | |
Converts any given object to unicode string. | |
>>> safeunicode('hello') | |
u'hello' | |
>>> safeunicode(2) | |
u'2' | |
>>> safeunicode('\xe1\x88\xb4') | |
u'\u1234' | |
""" | |
t = type(obj) | |
if t is unicode: | |
return obj | |
elif t is str: | |
return obj.decode(encoding, 'ignore') | |
elif t in [int, float, bool]: | |
return unicode(obj) | |
elif hasattr(obj, '__unicode__') or isinstance(obj, unicode): | |
try: | |
return unicode(obj) | |
except Exception as e: | |
return u"" | |
else: | |
return str(obj).decode(encoding, 'ignore') | |
# print safeunicode(any_thing) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment