[英]'\n' creates an indentation while parsing python code with ast.parse
I'm trying to parse with ast.parse in Python 3.7 ( https://docs.python.org/3/library/ast.html ) the following snippet of code: I'm trying to parse with ast.parse in Python 3.7 ( https://docs.python.org/3/library/ast.html ) the following snippet of code:
from functools import reduce
reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])
I use the code below:我使用下面的代码:
py_ast = """from functools import reduce \n reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])"""
py_ast = ast.parse(py_ast)
And i got this error:我得到了这个错误:
File "", line 2 --> reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5]) IndentationError: unexpected indent
文件“”,第 2 行 --> reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5]) IndentationError: 意外缩进
I understand the use of \n
is creating an indent, how can I avoid it?我知道使用
\n
是创建缩进,我该如何避免它?
You're using triple quotes so why not leave out the \n altogether and just hit enter, the string will stay formatted how you want it.您正在使用三引号,所以为什么不完全省略 \n 并按回车键,字符串将保持您想要的格式。
This code runs fine for me:这段代码对我来说运行良好:
import ast
py_ast = """from functools import reduce
reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])"""
py_ast = ast.parse(py_ast)
print(py_ast)
>>> <ast.Module object at 0x0000019F2E140FD0>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.