Python生成C++代码时f-string插入变量后缩进异常如何解决?
解决方案
标准库原生方案(无需额外安装依赖)
Python标准库textwrap自带indent方法,刚好和你在用的dedent配对使用:dedent负责标准化代码片段、移除公共前导缩进,indent负责给子代码片段统一添加指定前缀的缩进,完全不需要手动计算每行的空格数。
修改后的可运行代码如下:
import textwrap # 子代码片段标准化为无公共前导缩进的格式 cpp_body = textwrap.dedent(""" a[i] *= 2; b[i] /= 4.5; """) # 插入时用textwrap.indent给子片段添加对应层级的缩进即可 cpp_loop = textwrap.dedent( f""" for (int i = 0; i < 10; i++) {{ {textwrap.indent(cpp_body, ' ')} }} """ ) print(cpp_loop)
运行后输出完全符合预期:
for (int i = 0; i < 10; i++) { a[i] *= 2; b[i] /= 4.5; }
如果想要彻底省去手动指定缩进字符的步骤,可以写一个简单的辅助模板函数,自动识别占位符前的缩进量:
import textwrap import re def render_code(template: str, **kwargs) -> str: template = textwrap.dedent(template) # 自动匹配占位符前的缩进量,给插入内容统一添加 def replace(match): indent = match.group(1) var = match.group(2) return textwrap.indent(kwargs[var], indent) return re.sub(r'^(\s+){{(\w+)}}', replace, template, flags=re.MULTILINE) # 使用示例 cpp_body = textwrap.dedent(""" a[i] *= 2; b[i] /= 4.5; """) # 模板里占位符前面加多少缩进,最终输出就自动同步多少 cpp_loop = render_code(""" for (int i = 0; i < 10; i++) { {{cpp_body}} } """, cpp_body=cpp_body)
第三方方案(适合复杂代码生成场景)
如果需要生成多层嵌套、结构复杂的代码,推荐用Jinja2模板引擎,它自带缩进处理能力,还支持循环、条件判断等逻辑,适配更复杂的生成需求:
- 安装依赖:
pip install jinja2 - 使用示例:
from jinja2 import Template # 模板里直接按需要的格式写占位符即可 tpl = Template(""" for (int i = 0; i < 10; i++) { {{ cpp_body | indent(4) }} } """) cpp_body = """ a[i] *= 2; b[i] /= 4.5; """ cpp_loop = tpl.render(cpp_body=cpp_body.strip()) print(cpp_loop)
内容的提问来源于stack exchange,提问作者Curious
相关产品推荐
相关产品推荐

