首页 > 解决方案 > Python 2.7 中带有 UTF8 的模板字符串

问题描述

请我需要有关 python 2.7 的帮助。from string import Template 如果我在没有模板工作良好的情况下打印字符串并且如果我在模板下打印它会出现错误,我会使用Unicode 并出现错误

AH01215: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 8: ordinal not in range(128)

我的例子:2个文件:

template.py我使用这段代码

#!/usr/bin/python
# -*- coding: utf-8 -*-
########################################################
#
from string import Template
ABC = Template("""<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
Hello ${NAME}""")

index.py我使用这个代码

#!/usr/bin/python
# -*- coding: utf-8 -*-
########################################################
import template
print "Content-Type: text/html\n"
ZXC = "m’a réveillé"
print template.ABC.substitute(dict(NAME=ZXC))

如果我使用此代码会出现上面的错误,并且如果我直接打印它而不在模板下print ZXC运行良好

如何在模板下修复这个utf8?

标签: pythonpython-2.7python-templates

解决方案


在给模板提供特殊字符之前,需要对它们进行转义。但首先指定字符串是 unicode。我相信你index.py应该成为:

#!/usr/bin/python
# -*- coding: utf-8 -*-
########################################################
import template
print "Content-Type: text/html\n"
ZXC = u"m’a réveillé".encode('ascii', 'xmlcharrefreplace')
print template.ABC.substitute(dict(NAME=ZXC))

推荐阅读