Search code examples
pythonjinja2non-ascii-characters

Printing non-ascii characters in python/jinja


The following code works correctly:

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)

The error is:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 10: ordinal not in range(128)

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.


Solution

  • I figured it out. The key is to do str.encode('string-escape')

    So, I did this:

    template = Template('{{ list[0].encode("string-escape") }}')
    

    And that worked.