I think I'm going crazy with Python's unicode strings. I'm trying to encode escape characters in a Unicode string without escaping actual Unicode characters. I'm getting this:
In [14]: a = u"Example\n"
In [15]: b = u"Пример\n"
In [16]: print a
Example
In [17]: print b
Пример
In [18]: print a.encode('unicode_escape')
Example\n
In [19]: print b.encode('unicode_escape')
\u041f\u0440\u0438\u043c\u0435\u0440\n
while I desperately need (English example works as I want, obviously):
In [18]: print a.encode('unicode_escape')
Example\n
In [19]: print b.encode('unicode_escape')
Пример\n
What should I do, short of moving to Python 3?
PS: As pointed out below, I'm actually seeking to escape control characters. Whether I need more than just those will have to be seen.
The method
.encode
returns a byte-string (typestr
in Python 2), so it cannot return unicode characters.But as there are only few \ - sequences you can easily
.replace
them manually. See http://docs.python.org/reference/lexical_analysis.html#string-literals for a complete list.First let's correct the terminology. What you're trying to do is replace "control characters" with an equivalent "escape sequence".
I haven't been able to find any built-in method to do this, and nobody has yet posted one. Fortunately it's not a hard function to write.
Or the slightly less readable one-liner version:
Backslash escaping ascii control characters in the middle of unicode data is definitely a useful thing to try to accomplish. But it's not just escaping them, it's properly unescaping them when you want the actual character data back.
There should be a way to do this in the python stdlib, but there is not. I filed a bug report: http://bugs.python.org/issue18679
but in the mean time, here's a work around using translate and hackery:
All the non-backslash-single-letter control characters will be escaped with the \x## sequence, but if you need something different done with those, your translation matrix can do that. This approach is not lossy though, so it works for me.
But getting it back out is hacky too because you can't just translate character sequences back into single characters using translate.
you actually have to encode the characters that map to bytes individually using latin1 while backslash escaping unicode characters that latin1 doesn't know about so that the unicode_escape codec can handle reassembling everything the right way.
UPDATE:
So I had a case where I needed this to work in both python2.7 and python3.3. Here's what I did (buried in a _compat.py module):
.encode('unicode_escape')
returns a byte string. You probably want to escape the control characters directly in the Unicode string:Output:
Note there are other Unicode control characters beyond 0-31, so you may need something more like:
Output:
You may want finer control of what is considered a control character. There are a number of categories. You could build a regular expression matching a specific type with: