这可能适用于所有具有转义字符的语言,但我在Python(3.4.2)中做了一个例子。你怎么逃避这个:
警告:请勿使用此代码,这只是一个示例
#unescaped for examples sake, and using solely " instead of '
eval("eval("print("Hi")")")
这不会起作用:
>>> 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
这也不会起作用:
>>> eval("eval(\"print(\\"Hi\\")\")")
SyntaxError: invalid syntax
那你怎么逃避呢?
答案 0 :(得分:1)
使用三个反斜杠(\\\
)
eval("eval(\"print(\\\"Hi\\\")\")")
说明:
在eval("eval(\"print(\\\"Hi\\\")\")")
中,传递的字符串是:
"eval(\"print(\\\"Hi\\\")\")"
评估字符串时,将删除所有转义字符。这会将"\\"
变为\
,将"\""
变为"
。所以,你最终得到:
eval("print(\"Hi\")").
(这会评估"print(\"Hi\")"
,这只是print("Hi")
。)
请注意:
>>> 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