Skip to content

Instantly share code, notes, and snippets.

@dawn110110
Last active August 29, 2015 14:01
Show Gist options
  • Save dawn110110/ca711e39841142256b57 to your computer and use it in GitHub Desktop.
Save dawn110110/ca711e39841142256b57 to your computer and use it in GitHub Desktop.
Safe unicode function(modified from web.py)
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