Skip to content

Instantly share code, notes, and snippets.

@5263
Created September 25, 2014 09:13
Show Gist options
  • Save 5263/8faa53505a85bcf3c1e5 to your computer and use it in GitHub Desktop.
Save 5263/8faa53505a85bcf3c1e5 to your computer and use it in GitHub Desktop.
encode unicode with name literals
import unicodedata
def encodechar(c):
i=ord(c)
if i >= 32 and i <=122 and \
c not in '\'\"/\\^_~`|':
return c
else:
if not isinstance(c,unicode):
c=unicode(c)
name = unicodedata.name(c,None)
if name:
return '\\N{%s}' % name
else:
return c.encode('unicode-escape')
def encodestr(s):
return u''.join(encodechar(c) for c in s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment