You have some string input with some specical characters escaped using syntax rules resemble Python's. For example the 2 characters '\n' stands for the control character LF. You need to decode these control characters efficiently. Use Python's builtin codecs to decode them efficiently.
Python, 36 lines
Python's builtin codecs not only decode various character encoding to unicode, it also has a number of codecs that does useful transformation, such as base64 encoding. In this case the 'string_escape' codecs would decode string literal as in Python source code. These builtin codecs are presumably highly optimized. They should be lot more efficient compares to looking them up character by character with pure Python code.
In case of unicode string, there is a seemingly parallel 'unicode_string' codecs. However when we apply this to non-ASCII string it runs into problem.
The issue is unlike 'string_escape', which convert from byte string to byte string, 'unicode_escape' decode byte string into unicode. If the operand is unicode, Python tries to convert it using system encoding first. This causes failures in many cases.
Steven Bethard has proposed a 3 steps decoding on the comp.lang.python newsgroup http://groups.google.com/group/comp.lang.python/browse_frm/thread/2c695421c1697432/72a8619ee3fc2631?q=string_escape&rnum=2#72a8619ee3fc2631. It resolves this problem by first encode the unicode string using UTF-8, then applies string_escape, and finally decode it back using UTF-8. This procedure is shown in the second algorithm of the recipe.
Due diligence on UTF-8 encoding
Before we call the problem solved, we should examine the possibility that the UTF-8 encoding might introduces bytes sequences that match Python string escape accidentally, and thus corrupts the output. A careful look in the mechanism of UTF-8 encoding assures us this will not happen.
UTF-8 - Wikipedia http://en.wikipedia.org/wiki/Utf-8 A byte sequence for one character never occurs as part of a longer sequence for another character. For instance, US-ASCII octet values do not appear otherwise in a UTF-8 encoded character stream.
From Python documentation http://www.python.org/doc/current/ref/strings.html, all string escapes are defined by ASCII characters.
Since non-ASCII character would not appears in UTF-8 encoded stream as ASCII octet, it would not introduce extra Python escapes by accident.
For comparison, notice how a valid unicode character \u5c6e would be mistaken as Python escape \n in UTF-16 encoding.