简体   繁体   English

'\n' 在使用 ast.parse 解析 python 代码时创建缩进

[英]'\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.

相关问题 SyntaxError:使用ast.parse扫描字符串文字时出现EOL - SyntaxError: EOL while scanning string literal with ast.parse 在 python 中不使用 ast.parse 从组成元素生成 ast - Generate ast from constituent elements without using ast.parse in python 如何在交互式Shell中使用ast.parse()解析文件 - How to use ast.parse() inside interactive shell to parse a file ast.parse的filename参数有什么用? - What's the use of the filename parameter of ast.parse? 函数ast.parse和ast.walk期间的IndentationError - IndentationError during `ast.parse` and `ast.walk` of a function which is a method inside class 通过 ast.Parse、compile 和 exec 使用“self”访问实例变量 - Accessing instance variables using "self" via ast.Parse, compile, and exec Python 源代码解析:“运行时自省解析”与“AST 解析” - Python source code parsing: “runtime introspection parsing” versus “AST parsing” 如何阻止`ast.parse` 将数值转换为整数/浮点数? - How to stop `ast.parse` from converting numerical values into int/floats? Python 用于将任何语言的代码解析为 AST 的库? - Python library for parsing code of any language into an AST? 如何解析 python 代码并且只获取没有缩进的变量? - How to parse python code and only get variables with no indentation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM