Reversing \N{...} notation?

Peter Otten __peter__ at web.de
Tue Oct 25 14:14:14 EDT 2016


Tim Chase wrote:

> I like the clarity of using the "\N{...}" notation when creating
> string literals involving Unicode chars.
> 
> Is there a built-in way to get such strings back from Python?
> 
>  >>> s = 'ma\N{LATIN SMALL LETTER N WITH TILDE}ana'
>  >>> s
>  'mañana'
>  >>> magic(s)
>  'ma\\N{LATIN SMALL LETTER N WITH TILDE}ana'
> 
> I can manually rip the string apart and put it back together with
> something like
> 
>  >>> import unicodedata as ud
>  >>> ''.join(c if ord(c) < 128 else '\\N{%s}' % ud.name(c) for c in s)
> 'ma\\N{LATIN SMALL LETTER N WITH TILDE}ana'
> 
> but was wondering if there was some sort of .encode() trick or other
> corner of the library I hadn't found.

>>> 'mañana'.encode("ascii", "namereplace").decode()
'ma\\N{LATIN SMALL LETTER N WITH TILDE}ana'

(requires Python 3.5)





More information about the Python-list mailing list