'string_escape' in python 3

Ian Kelly ian.g.kelly at gmail.com
Fri Apr 6 19:04:55 EDT 2012


On Fri, Apr 6, 2012 at 4:19 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> I actually thought of that, but assumed that adding enclosing quotes would
> be safe (or that the OP trusted the string). After sending, I realized that
> if Nasty Hacker guessed that the string would be so augmented, then it would
> not be safe. This or above with literal_eval is.
>
>>>> ast.literal_eval("'{}'".format('\x3a'))
> ':'

That version is safe from injection, but it will still choke on things
that string_escape can process successfully:

>>> s = "Isn't it wonderful?"
>>> s.decode('string_escape')
"Isn't it wonderful?"
>>> ast.literal_eval("'" + s + "'")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python27\lib\ast.py", line 49, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "c:\python27\lib\ast.py", line 37, in parse
    return compile(expr, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    'Isn't it wonderful?'
         ^
SyntaxError: invalid syntax

Of course you could use different string delimiters, but then you just
fail on different strings.



More information about the Python-list mailing list