1

I am working on a project in python, and have encountered an error.

When I try to run this code: eval("print(\"\n\")"), it doesn't work and gives me an error: 'SyntaxError: EOL while scanning string literal'. But when I replace the '\n' with a 'Hello World', as shown in this code: eval("print(\"Hello World\")"), it prints the correct output.

Why is this? I would appreciate any thoughts on the issue so that I can continue working on my project. Thanks in advance.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 3
    It is seen as real newline (end of line, EOL) in the code processed by `eval`. Try `eval("print(\"\\n\")")` – Michael Butscher Jul 25 '23 at 16:01
  • 3
    Though on a different note: why are you using `eval`? If you're learning Python, that's one of the functions to stay far away from, no good code comes from using it. – Mike 'Pomax' Kamermans Jul 25 '23 at 16:09
  • @Mike *"no good code comes from using it"* -- There are niche cases, like [my answer on "Print self-documenting expression with value of variable on a new line"](/a/76335376/4518341). But yeah, best to stay away from it as a beginner. – wjandrea Jul 25 '23 at 16:26
  • No good code can come from eval. Only "this can be done better without eval" or "very clever code written by someone with a deep understanding of Python that is going to frustrate future maintainers" =) – Mike 'Pomax' Kamermans Jul 25 '23 at 16:30
  • I have tried to print `eval('print("\n")')` and get `SyntaxError: unterminated string literal`, but `print("\n")` works as expected. – Hermann12 Jul 25 '23 at 16:40

2 Answers2

1

In eval("print(\"\n\")"), the backslash \ before the n character is considered an escape character in Python strings hence it represents the newline character not the actual characters \ and n

To fix this,

eval("print(\"\\n\")") - use a double backslash \\

0

How eval() function works:

  • Parse expression
  • Compile it to bytecode
  • Evaluate it as a Python expression
  • Return the result of the evaluation

The print() expression will return None.

So if you would only a linbreak from eval():

print('before')
eval(repr(print("\n")))
print('after')

Output:

before


after

This results the same as:

print('before')
print("\n")
print('after')
Hermann12
  • 1,709
  • 2
  • 5
  • 14