python - 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个文件:
- 索引.py
- 模板.py
在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?
解决方案
在给模板提供特殊字符之前,需要对它们进行转义。但首先指定字符串是 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))
推荐阅读
- jenkins - Is it possible to execute shell with parameterized remote ip?
- amazon-web-services - 用于分区大数据的最佳 AWS 实例
- html - 当我展开窗口时,ggplotly & Plotly 缺失值
- objective-c - NSAppleScript 使用给定的 NSRange 突出显示任何 Mac 应用程序中的文本
- php - Laravel 5.7:类 setQueue 不存在
- python-3.x - 获取 Series' 对象没有属性 'split'", '从推文中删除常用词时在索引 id 处发生
- javascript - HTML 将剪贴板文件粘贴到文件输入
- javascript - 角度登录表单验证
- python - 比较和匹配最近的时间,Python
- android - 苹果是否要求您为 iBeaons 提供一些特殊的芯片?