Jayendra Parmar
Jayendra Parmar

Reputation: 774

SyntaxError: EOL while scanning string literal with ast.parse

The following the valid python code

In [49]: print('hello\n')
hello

but when I use ast module's parse method it returns, the Syntax error

In [47]: code = "print('hello\n')"

In [48]: ast.parse(code)
  File "<unknown>", line 1
    print('hello
           ^
SyntaxError: EOL while scanning string literal

In [51]: eval(code)
  File "<string>", line 1
    print('hello
        ^
SyntaxError: invalid syntax

why is ast module not able to parse the valid python code in this case?

Upvotes: 0

Views: 5000

Answers (3)

Sunitha
Sunitha

Reputation: 12015

You have to escape the \ in code

code = "print('hello\\n')"
ast.parse(code)
# <_ast.Module object at 0x7fd68cb48cc0> 

Or you can add r prefix to indicate everything in the string needs to be escaped

code = r"print('hello\n')"
ast.parse(code)
# <_ast.Module object at 0x7fd68cb48ef0>

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

You need to use multiline comment '''YourCode''' or """YourCode"""

Ex:

import ast
code = "print('''hello\n''')"
print(ast.parse(code))

Upvotes: 1

Gelineau
Gelineau

Reputation: 2090

You should write:

code = "print('hello\\n')"

Upvotes: 1

Related Questions