Python编码问题(ascii>;unicode)
我有一个典型的utf-8编码问题,但到目前为止,我还不能解决它Python编码问题(ascii>;unicode),python,google-app-engine,utf-8,python-2.7,Python,Google App Engine,Utf 8,Python 2.7,我有一个典型的utf-8编码问题,但到目前为止,我还不能解决它 class StatsTandE(webapp2.RequestHandler): def get(self): conn = rdbms.connect(instance=_INSTANCE_NAME, database='origami') cursor = conn.cursor() cursor.execute('SELECT ui.displayName, ui.title, ui.costC
class StatsTandE(webapp2.RequestHandler):
def get(self):
conn = rdbms.connect(instance=_INSTANCE_NAME, database='origami')
cursor = conn.cursor()
cursor.execute('SELECT ui.displayName, ui.title, ui.costCenter FROM views AS v')
results = [[str(row[0]), str(row[1]), str(row[2])] for row in cursor.fetchall()]
logging.info('results identified as %s', results)
template_file_name = 'templates/stats_results.html'
template_values = {
'results': results,
}
path = os.path.join(os.path.dirname(__file__), template_file_name)
self.response.out.write(template.render(path, template_values))
conn.close()
我看到的错误是:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 4: ordinal not in range(128)
将str(行[0])
更改为str(行[0])。编码('utf-8')
无效
有什么建议吗?尝试将str(第[0]行)更改为unicode(第[0]行)
更新:正如其他人所说:除非您需要,否则您甚至不应该使用unicode
和str
。只需尝试行[0],行[1],行[2]
。当您需要显示它时,请执行以下操作:行[0]。编码('utf8')
您使用的是哪个版本的python?无论您使用的是python 2.X还是python 3,Unicode问题都以不同的方式得到解决。如果字符串将包含UTF-8字符,则应使用python 2中的Unicode
数据类型。我们使用的是python 2.7。如何设置unicode
数据类型?如果删除所有str
调用会发生什么?表示文本的数据的一般规则:在输入时尽快从字节转换为Unicode,在程序中的任何地方都使用Unicode,在输出时尽可能晚地从Unicode转换为字节。这很有效!但是,如何将unicode再次转换为字符串,以便在页面上显示良好?我能再破译一遍吗?