在python/jinja中打印非ASCII字符 [英] Printing non-ascii characters in python/jinja
本文介绍了在python/jinja中打印非ASCII字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码正常工作:
from jinja2 import Template
mylist = ['some text \xc3']
template = Template('{{ list }}')
print template.render(list=mylist)
当我运行它时,它输出:
When I run it, it outputs:
['some text \xc3']
但是,当我尝试打印实际的列表元素时,它失败了:
Yet, when I try to print the actual list element, it fails:
template = Template('{{ list[0] }}')
print template.render(list=mylist)
错误是:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 10: ordinal not in range(128)
我想找到一种方法来打印单个列表元素,就像打印整个列表一样,其中非ASCII字符用\ x表示.
I would like to find a way to print the individual list element in the same way that the whole list is printed, where the non-ascii character is represented with the \x notation.
推荐答案
我知道了.关键是要做str.encode('string-escape')
I figured it out. The key is to do str.encode('string-escape')
所以,我这样做了:
template = Template('{{ list[0].encode("string-escape") }}')
那行得通.
这篇关于在python/jinja中打印非ASCII字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文