Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Jinja2 ASCII转换为字符串_Python_C++_Jinja2_Systemc - Fatal编程技术网

Python Jinja2 ASCII转换为字符串

Python Jinja2 ASCII转换为字符串,python,c++,jinja2,systemc,Python,C++,Jinja2,Systemc,我的Jinja2模板中有一行: {% for type in types %} top -> {{(loop.index0 + 'a')|string}}(var{{loop.index0}}); {% endfor %} 类型是C++中的各种类型的列表,在模板中其他地方使用,输出是SystemC程序初始化模块信号的一部分。 目标是获得如下输出,其中字符以小写字母a开头: top -> a(var0); top -> b(var1); 但是,它给出了以下错误:“不支

我的Jinja2模板中有一行:

{% for type in types %}
    top -> {{(loop.index0 + 'a')|string}}(var{{loop.index0}});
{% endfor %}

类型是C++中的各种类型的列表,在模板中其他地方使用,输出是SystemC程序初始化模块信号的一部分。 目标是获得如下输出,其中字符以小写字母a开头:

top -> a(var0);
top -> b(var1);
但是,它给出了以下错误:“不支持+:'int'和'str'的操作数类型”,因此我尝试将模板更改为:

{% for type in types %}
    top -> {{(loop.index0 + 'a'|int)|string}}(var{{loop.index0}});
{% endfor %}
但结果是这样的

top -> 0(var0);
top -> 1(var1);

问题似乎在于,在Jinja2模板中,无法将整数转换为相应的ASCII字符。我尝试了“chr()”,但这是一个Python函数,不是Jinja2函数,无法工作。我想知道是否有人有这方面的经验,可以帮助我吗?

a和b是你喜欢的类型吗?如果是这样,您可以直接使用它们的字符串值:

template.cpp

{% for type in types %}
top -> {{type}}(var{{loop.index0}});
{% endfor %}
main.py

import jinja2
import os.path
template_dir = os.path.dirname(__file__)
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
                               autoescape = False)

t = jinja_env.get_template('template.cpp')
types = ['a', 'b', 'c']
print (t.render(types=types))
运行的main.py输出:

top -> a(var0);

top -> b(var1);

top -> c(var2);

回答标题问题:“Jinja2 ASCII到字符串”

“类型”列表实际上只是一个指示元素数量的列表。a、 b、c等不是类型,而是模块变量的名称。类型列表看起来是这样的:类型=['uint32_t','char','float'],但是,我确实意识到我可以使用另一个列表,它只包含所有小写字母,因此它将是{%for type in types%}top->{{letters[loop.index0]}(var{{loop.index0});{%endfor%}
# Returns "a" if 'my_index' is 0, "b" if 1, etc.
{{ "abcdefghijklmnopqrstuvwxyz"[my_index] }}

# Use the char_code as the index.
{{ "abcdefghijklmnopqrstuvwxyz"[char_code - 97] }}