专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Perl/Python

python列表内容中文编码有关问题

发布时间:2011-06-29 20:09:53 文章来源:www.iduyao.cn 采编人员:星星草
python列表内容中文编码问题
>>> li=['sd','你好']
>>> print li
['sd', '\xe4\xbd\xa0\xe5\xa5\xbd']
>>> li[1].decode('gbk')
u'\u6d63\u72b2\u30bd'
>>> li[1].decode('utf-8')
u'\u4f60\u597d'
>>> unicode(li[1],'gbk')
u'\u6d63\u72b2\u30bd'
>>> li[1].decode('gb2312')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 2-3: illegal multibyte sequence

请问如何才能将li中的内容显示成中文呢?项目需要即将li[1]与中文字符串比较,但是li[1]是乱码该如何解决呢?

------解决方案--------------------
str.find(u'你好')可以在str这个string中查找中文
------解决方案--------------------
Python code

li=['sd','你好']
li
['sd', '\xc4\xe3\xba\xc3']
print li[1]
你好
li[1]=='你好'
True
li[1]=='你好a'
False

------解决方案--------------------
Python code

[root@RHEL6A temp]# python
Python 2.6.5 (r265:79063, Jul 14 2010, 11:36:23) 
[GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> li=['sd','你好']
>>> li
['sd', '\xe4\xbd\xa0\xe5\xa5\xbd']
>>> print li[1]
你好

------解决方案--------------------
print li打印出数据存储的编码方式,中文是中文编码;
print li[1]打印出的是译转中文编码的中文。
------解决方案--------------------
探讨

Python code

[root@RHEL6A temp]# python
Python 2.6.5 (r265:79063, Jul 14 2010, 11:36:23)
[GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2
Type "help", "copyright", "credits" or "license" for more ……

------解决方案--------------------
探讨
>>> li=['sd','你好']
>>> print li
['sd', '\xe4\xbd\xa0\xe5\xa5\xbd']
>>> li[1].decode('gbk')
u'\u6d63\u72b2\u30bd'
>>> li[1].decode('utf-8')
u'\u4f60\u597d'
>>> unicode(li[1],'gbk')
u'\u6d63\u72……
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: