Interpreting \ escape sequences in strings
Peter Otten
__peter__ at web.de
Sun Mar 14 18:12:19 EST 2004
Paul Watson wrote:
> However, I am in a Python 2.1 environment. Do you know of any techniques
> that would work under Python 2.1?
eval('"' + s + '"')
This of course requires that " chars occuring in s are preceded by a
backslash:
>>> def unescape(s):
... return eval('"' + s + '"')
...
>>> unescape("\\x0a")
'\n'
>>> unescape("\\x0a'")
"\n'"
>>> unescape("\\x0a\"")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in unescape
File "<string>", line 1
"\x0a""
^
SyntaxError: invalid token
>>> unescape('\\x0a\\"')
'\n"'
Peter
More information about the Python-list
mailing list