What is the purpose of the ("\\n") in the following line?
exec("""\ntarget.write(line1)\ntarget.write("\\n")\ntarget.write(line2)\ntarget.write("\\n")\ntarget.write(line3)\ntarget.write("\\n..")\n""")
\ has a special meaning in Python. So you have to escape it if you want to print it.
Printing single \ is not going to work that way because you are escaping the close quote
>>> print("\")
File "<stdin>", line 1
print("\")
^
SyntaxError: EOL while scanning string literal
As it is here.
>>> print("\"")
"
To print \ you have to escape it with another \
>>> print("\\")
\
Here you cannot escape 's' because '\s' do not have special mieaning.
>>> print("\s")
\s
But '\n' represents a new line character.
>>> print("\n")
So to print \n you have to escape the \
>>> print("\\n")
\n
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"')
>>>
(Feb-20-2018, 11:48 PM)Dixon Wrote: [ -> ]What is the purpose of the ("\\n") in the following line?
exec("""\ntarget.write(line1)\ntarget.write("\\n")\ntarget.write(line2)\ntarget.write("\\n")\ntarget.write(line3)\ntarget.write("\\n..")\n""")
target
isn't defined, so it doesn't matter as you'll get an error anyway. Yet another reason you should never use
eval
or
exec
.