Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
\\n in code
#3
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"')


>>>
Reply


Messages In This Thread
\\n in code - by Dixon - Feb-20-2018, 11:48 PM
RE: \\n in code - by wavic - Feb-20-2018, 11:58 PM
RE: \\n in code - by abhin - Feb-21-2018, 02:59 AM
RE: \\n in code - by nilamo - Mar-22-2018, 07:19 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020