Reputation:
This probably applies to all languages that have escape characters, but I'm making an example with Python (3.4.2). How would you escape this:
Warning: Do not use this code ever, this is just an example
#unescaped for examples sake, and using solely " instead of '
eval("eval("print("Hi")")")
This won't work:
>>> eval("eval(\"print(\"Hi\")\")")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
eval("eval(\"print(\"Hi\")\")")
File "<string>", line 1
eval("print("Hi")")
^
SyntaxError: invalid syntax
This also won't work:
>>> eval("eval(\"print(\\"Hi\\")\")")
SyntaxError: invalid syntax
So how would you escape it?
Upvotes: 0
Views: 365
Reputation:
Escape with three backslashes (\\\
)
eval("eval(\"print(\\\"Hi\\\")\")")
Explanation:
In eval("eval(\"print(\\\"Hi\\\")\")")
, the string being passed is:
"eval(\"print(\\\"Hi\\\")\")"
When the string is evaluated, all the escape characters are removed. This turns "\\"
into \
and "\""
into "
. So, you end up with:
eval("print(\"Hi\")").
(This evaluates "print(\"Hi\")"
, which is just print("Hi")
.)
Note this:
>>> len("\\") # Escaped letters are on character
1
>>> len("\n")
1
>>> len("nn")
2
>>> "\'" == "'" == '\'' # Various forms of escaped '
True
>>> "\n" == """
""" # Multiline string with a newline
True
>>> "\q" == "q" # q is not escapeable
False
>>> "\q"
'\\q'
>>> len("\q")
2
Upvotes: 1