在开发/本地机器上运行的 Python 代码,但在安装到 Appengine 后失败:
我文件中的第一行:
# -*- coding: utf8 -*-O
代码后面的行:
s1 = u'Ismerőseid'
logging.info (s1)
s2 = s1 + u':' + s1
logging.info (s2)
logging.info ("%s,%s", s1, s2)
在开发中(本地主机):
INFO 2012-12-18 04:01:17,926 AppRun.py:662] Ismerőseid,
INFO 2012-12-18 04:01:17,926 AppRun.py:664] Ismerőseid:Ismerőseid
INFO 2012-12-18 04:01:17,926 AppRun.py:665] Ismerőseid,Ismerőseid. Ó,
安装/运行后在 App Engine 上:
I 2012-12-21 06:52:07.730
É, Á, Ö, Ü. Ó,
E 2012-12-21 06:52:07.736
Traceback (most recent call last):
File "....", line 672, in xxxx
s3 = s1 + u':' + s1
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)
我尝试了编码/解码/等的各种组合。我也对粘贴的字符串 'Ismerőseid' 进行了检查,它给了我 {'confidence': 0.7402600692642154, 'encoding': 'ISO-8859 -2'}
非常感谢任何帮助!
最佳答案
将这 3 行放在 Python 27 代码的顶部以使用 unicode:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# And this code will not give you any problems
s1 = 'É, Á, Ö, Ü. Ó,'
logging.info (s1)
s2 = s1 + ':' + s1
logging.info ("%s,%s", s1, s2)
永远不要使用 str()。仅当您确实需要时!
并阅读 this blogpost来自尼克·约翰逊。这是在 Python 27 之前。他没有使用 from __future__ import unicode_literals
,这使得在 Python 中使用 unicode 变得如此容易。
关于google-app-engine - App Engine 中的 Python unicode 字符串操作失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13989860/