Reputation: 73
I have a string representation of the code, like the example given below
code='''
print('\n')
print('hello world')
'''
import ast
ast.parse(code)
Throws an error
print("
^
SyntaxError: EOL while scanning string literal
The new line character seems to be pushing the single quote to the next line before parse.Escaping '\n' solves the issue, but this would require looping through each line in the string. Is there a better way to do this ?
Upvotes: 0
Views: 791
Reputation: 597
What seems to be happening is your 'code' is being interpreted by python before it can be parsed by ast. You can pass it as a raw string by putting an 'r' before the string and it seems to work;
code=r'''
print('\n')
print('hello world')
'''
import ast
ast.parse(code)
Upvotes: 3