Reversing \N{...} notation?

Serhiy Storchaka storchaka at gmail.com
Thu Oct 27 04:36:03 EDT 2016


On 26.10.16 23:47, Peter Otten wrote:
>     def mynamereplace(exc):
>         return u"".join(
>             "\\N{%s}" % unicodedata.name(c)
>             for c in exc.object[exc.start:exc.end]
>         ), exc.end
>     codecs.register_error("namereplace", mynamereplace)

Not all characters has standard name. This fails with say '\x80'. Use 
backslash escaping as a fallback:

try:
     ascii
except NameError:
     ascii = repr
def mynamereplace(exc):
     repl = []
     for c in exc.object[exc.start:exc.end]:
         try:
             repl.append("\\N{%s}" % unicodedata.name(c))
         except ValueError:
             repl.append(ascii(c)[1:-1])
     return u"".join(repl), exc.end





More information about the Python-list mailing list