python2.7 的中文处理 报错,已解决,求大大解释原因

2015-04-21 00:27:23 +08:00
 twor2
# -*- coding: utf-8 -*-
from django.utils.encoding import  python_2_unicode_compatible

@python_2_unicode_compatible
class Label(models.Model):
    width = models.ForeignKey(PaperWidth, verbose_name='宽度')
    height = models.ForeignKey(PaperHeight, verbose_name='高度')

    def __str__(self):
        return u'{0}({1}×{2})'.format(self.paper_type, self.width, self.height)

这个是一个 python 2.7,django1.8 的程序

之前 verbose_name=u'宽度' 在添加 @python_2_unicode_compatible 就去掉u了,没有问题

但下面的 return u'{0}({1}×{2})' 为什么不能去掉呢?去掉就报错

'ascii' codec can't decode byte 0xe9 in position 0
3744 次点击
所在节点    Python
13 条回复
ryd994
2015-04-21 01:26:14 +08:00
python3大法好 utf8保平安
其实是)是全角字符的原因
换成)就好
ryd994
2015-04-21 01:26:50 +08:00
另外乘号也是,别告诉我你不知道要用*
twor2
2015-04-21 01:29:55 +08:00
@ryd994 谢谢亲的回答

那为什么上面的 中文(比如 ’宽度‘) 就可以不加 u 呢

这个 @python_2_unicode_compatible 不能解决 全角字符吗?
twor2
2015-04-21 01:35:50 +08:00
```
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.

To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if six.PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
```
twor2
2015-04-21 01:38:54 +08:00
看不懂~~
no13bus
2015-04-21 08:58:56 +08:00
@twor2 记着 中文前面加 u 就行了。还有不知道你现在的系统是什么,不要在windows下面开发python程序。
zerh925
2015-04-21 09:35:26 +08:00
可以试试'宽度'.encode('utf-8')
iamxi
2015-04-21 10:09:36 +08:00
如果你用win8或以上,如果你的系统用户名是中文,如果你安装了阿里旺旺,我告诉你个秘密,你还会更痛苦。所以啊,要么在linux上开发,要么换python3吧。不然你会发现各种因为字符集问题引起的古怪的问题。比如pip不能安装,及时安装上了,pip也不能安装其他模块,等等。。。。
angeloce
2015-04-21 10:56:44 +08:00
原因很简单, python_2_unicode_compatible里写着呢.
通过__dict__得到函数内所有的变量, 不是unicode的就decode.
但是return xxxx 是在__dict__里得不到的, 你可以改成 result='{0}({1}×{2})'; return result 试试, 应该就可以了

P.S. django提供这种工具好无聊, python2还是尽量在字符前加u
twor2
2015-04-21 11:40:08 +08:00
@angeloce 恩,还有一点不明白

要访问类里的变量( 比如 width ),都要经过 return 吗?
twor2
2015-04-21 11:41:31 +08:00
@iamxi 我前几天用的python ,除了中文处理好一点,其他 的对于新手来说,坑更多。很多包都找不到,或者改名,或者替换。

心累
twor2
2015-04-21 11:42:32 +08:00
@zerh925
@no13bus 谢谢!,中文前面全加 u ,如果用了python3 是不是还要逐一去掉?
no13bus
2015-04-22 12:18:27 +08:00
@twor2 奥。没用过Python3. 不太清楚。编码问题自己搞明白了就好。3和2的区别不仅仅是编码。尽量用大家都用的版本,否则遇到问题了,不好解决

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/185097

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX