You want to pass some Python code to
exec
. So calling
exec
as
exec('print 5')
causes the Python interpreter to parse and run the print statement. But you knew all of that already.
What if you wanted to pass some Python code to
exec
that was intended to print a
\n
character? You couldn't call
exec('print "\n"')
because you're not passing the code
print "\n"
to
exec
; you're actually passing the following Python code to
exec
:
print "
"
That's not valid Python. In fact, here's what you'll see if you try to run
exec('print "\n"')
:
Python 2.7.10 (default, Jul 15 2017, 17:16:57)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> exec('print "\n"')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
print "
^
SyntaxError: EOL while scanning string literal
That's because you're asking
exec
to run invalid Python. So you want to escape the
\
in
exec('print "\n"')
by using
exec('print "\\n"')
instead. When you try to run that, you get:
>>> exec('print "\\n"')
>>>