【问题标题】:Template strings with UTF8 in Python 2.7Python 2.7 中带有 UTF8 的模板字符串
【发布时间】:2019-12-20 23:34:48
【问题描述】:

我需要有关 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 个文件:

  • index.py
  • template.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怎么解决?

【问题讨论】:

  • 嗨,试试这个:ZXC = u"m’a réveillé".encode('ascii', 'xmlcharrefreplace')

标签: python python-2.7 python-templates


【解决方案1】:

在输入模板之前需要转义特殊字符。 但首先指定字符串是 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))

【讨论】:

  • 感谢您的回复,我发现sql结果中的问题也必须添加.encode('UTF-8')
猜你喜欢
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-02
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多