gpt4 book ai didi

templates - 删除 Mako 模板中的前导空格

转载 作者:行者123 更新时间:2023-12-05 07:55:15 28 4
gpt4 key购买 nike

在从 Mako 模板自动生成代码的用例中,我希望有一个很好的语法来删除前导空格(类似于使用行尾的 \ 删除换行符)。

下面的代码

from mako.template import Template

# 1) Bad
print(Template(r'''
void myfunction(\
%for arg_name, arg_type in arguments:
${', ' if loop.index else ''}${arg_type} ${arg_name}\
%endfor
)
''').render(arguments=[('string', 'a'), ('int', 'b')]))

# 2) Good but ugly
print(Template(r'''
void myfunction(\
%for arg_name, arg_type in arguments:
<% %>${', ' if loop.index else ''}${arg_type} ${arg_name}\
%endfor
<%%>)
''').render(arguments=[('string', 'a'), ('int', 'b')]))

将打印这些结果:

void myfunction(        a string        , b int    )
void myfunction(a string, b int)

我想要后者的输出——那么有没有更好的语法同时仍然保持我的 Mako 模板很好地缩进?我的解决方案是空的 <% %>不是很漂亮。

最佳答案

这道题有很多主观词,比如beautifulnice,还有nicer。但我会试一试。让我知道这些是否符合您的要求。

请注意,以下两项都按照您的要求进行,但选项 #1 可能最容易阅读,但它也删除了 void 之前的所有空白,这可能不是预期的。选项 #2 应该能很好地满足您的描述。

使用下面的选项 #2,您可以替换您最喜欢的任何字符来表示应删除以下所有空格。

import re

# 1) Better?
print(Template(r'''
void myfunction(\
%for arg_name, arg_type in arguments:
${', ' if loop.index else ''}${arg_type} ${arg_name}\
%endfor
)
'''.replace(' ', '')).render(arguments=[('string', 'a'), ('int', 'b')]))

# 2) More Better?
print(Template(re.sub(r'>\s*', '', r'''
void myfunction(\
%for arg_name, arg_type in arguments:
> ${', ' if loop.index else ''}${arg_type} ${arg_name}\
%endfor
> )
''')).render(arguments=[('string', 'a'), ('int', 'b')]))

关于templates - 删除 Mako 模板中的前导空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30085728/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com